这是我的 App.js 代码:
function App() {
console.log('Rendering the App component');
const [someBooleanVar, updateBooleanVar] = React.useState(false);
console.log(someBooleanVar);
const clickHandler = () => {
console.log('In clickHandler');
console.log(someBooleanVar);
updateBooleanVar(true);
};
return (
<div className="app">
<h1>Test App</h1>
<button onClick={clickHandler}>Toggle</button>
</div>
);
}
ReactDOM.render(<App />, document.querySelector('#app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="app"></div>
当页面第一次加载时,我在控制台上看到以下内容:
Rendering the App component
App.js:12 false
现在,当我点击按钮时,控制台显示:
In clickHandler
App.js:16 false
App.js:8 Rendering the App component
App.js:12 true
如果我第二次点击按钮,控制台会输出:
In clickHandler
App.js:16 true
App.js:8 Rendering the App component
App.js:12 true
在随后的点击中,这些行会被打印出来:
In clickHandler
App.js:16 true
我的问题是:状态在第一次单击时就从 false 更新为 true。那么,为什么第二次单击会导致组件重新呈现,即使状态没有改变?
useEffect
钩子,每当someBooleanVar
更新时就执行它;useEffect
钩子仅在初始呈现后和第一次单击后执行两次:这表明状态确实只更新了一次,但是_为什么组件正在重新呈现?_ - Yousaf