React hooks 的奇怪行为:延迟数据更新 [英] Strange behavior of React hooks: delayed data update
问题描述
奇怪的行为:我希望第一个和第二个 console.log 显示不同的结果,但它们显示相同的结果,并且仅在下次单击时更改值.我应该如何编辑我的代码以使值不同?
function App() {const [count, setCount] = React.useState(false);const test = () =>{控制台日志(计数);//错误的setCount(!count);控制台日志(计数);//错误的};返回 (<div className="应用程序"><h1 onClick={test}>你好 StackOverflow</h1>
);}const rootElement = document.getElementById("root");ReactDOM.render(
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><div id="root"></div>
您可以在这里看到一个工作示例:https://codesandbox.io/s/wz9y5lqyzk
状态更新是异步的,所以如果你使用 Hooks,你可以使用 useEffect
在更新后收到通知.
这是一个例子:
https://codesandbox.io/s/wxy342m6l
如果你正在使用 React 组件的 setState,你可以使用回调
this.setState((state) => ({count: !state.count}), () => console.log('Updated', this.state.count));代码>
如果需要状态值,请记住使用回调来更新状态.
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>
You can see a working example here: https://codesandbox.io/s/wz9y5lqyzk
The state update is asynchronous so if you are using Hooks you can use useEffect
to be notified after an update.
Here is an example:
https://codesandbox.io/s/wxy342m6l
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));
Remember to use the callback to update state if you need a state value.
这篇关于React hooks 的奇怪行为:延迟数据更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!