状态更新是异步的。setCount
您从中获得的函数useState
无法神奇地伸出并更改count
常量的值。一方面,它是一个常数。另一方面,setCount
无法访问它。相反,当您调用 时setCount
,您的组件函数将再次被调用,并useState
返回更新后的计数。
现场示例:
const {useState} = React;
function Example() {
const [count, setCount] = useState(false);
const test = () =>{
setCount(!count); // Schedules asynchronous call to Example, re-rendering the component
};
return (
<div className="App">
<h1 onClick={test}>Hello CodeSandbox</h1>
<div>Count: {String(count)}</div>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
如果您需要在count
更改时执行一些副作用,请使用useEffect
:
useEffect(() => {
console.log(`count changed to ${count}`);
}, [count]);
请注意,我们告诉useEffect
仅在count
更改时调用我们的回调,这样如果我们有其他状态,我们的回调就不会不必要地运行。
现场示例:
const {useState, useEffect} = React;
function Example() {
const [count, setCount] = useState(false);
const test = () =>{
setCount(!count); // Schedules asynchronous call to Example, re-rendering the component
};
useEffect(() => {
console.log(`count changed to ${count}`);
}, [count]);
return (
<div className="App">
<h1 onClick={test}>Hello CodeSandbox</h1>
<div>Count: {String(count)}</div>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>