React钩子的奇怪行为:延迟的数据更新 [英] Strange behavior of React hooks: delayed data update
问题描述
奇怪的行为:我希望第一和第二个console.log显示不同的结果,但是它们显示相同的结果,并且仅在下次单击时更改该值.我应该如何编辑代码,以使值有所不同?
Strange behavior: I expect that the first and the second console.log display a different result, but they display the same result and the value is changed only on the next click. How should I edit my code so that the value will be different?
function App() {
const [count, setCount] = React.useState(false);
const test = () => {
console.log(count); //false
setCount(!count);
console.log(count); //false
};
return (
<div className="App">
<h1 onClick={test}>Hello StackOverflow</h1>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
您可以在此处看到一个有效的示例: https://codesandbox.io/s/wz9y5lqyzk
You can see a working example here: https://codesandbox.io/s/wz9y5lqyzk
推荐答案
状态更新是异步的,因此,如果您使用的是Hooks,则可以使用 useEffect
在更新后收到通知.
The state update is asynchronous so if you are using Hooks you can use useEffect
to be notified after an update.
这里是一个例子:
https://codesandbox.io/s/wxy342m6l
如果您使用的是React组件的setState,则可以使用回调
If you are using setState of a React component, you can use the callback
this.setState((state)=>({count:!state.count}),()=> console.log('Updated',this.state.count));
this.setState((state) => ({count: !state.count}), () => console.log('Updated', this.state.count));
请记住,如果需要状态值,请使用回调来更新状态.
Remember to use the callback to update state if you need a state value.
这篇关于React钩子的奇怪行为:延迟的数据更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!