问题描述
This.setState() 适用于我组件中的几乎所有变量,但不是全部.
This.setState() is working for almost all variables in my component, but not all.
当我尝试设置状态变量的状态时,值不会改变,这是一种非常奇怪的行为.
When i try to set the state of a state variable the value does not change which is a very strange behavior.
this.setState({ notSaved: size }, () => {
console.log(this.state.notSaved, 'notSaved','size',size);
});
}
console.log 的结果
Result of the console.log
这不是 setSate 的异步行为的问题,如下图所示,因为即使我 console.log 回调中的值,仍然保持不变.所以这不是一个重复的问题.
This is not a problem with the async behavior of the setSate, as you can see in the image below, because even if I console.log the value inside the callback, still unchanged. So this is not a duplicated question.
推荐答案
setState(updater[, callback])
在 setState 中使用回调来读取新值.setState
是异步的,您希望您的状态立即更新.为了确保您的状态得到更新,您必须利用作为第二个参数传入的回调函数.
use callback in setState to read new value. setState
is async and you are expecting your state to be updated instantly. To make sure your state got updated, you would have to leverage on call back function passed in as second argument.
this.setState((state, props) => {
return { notSaved: size }
}, () => console.log(this.state.notSaved, 'updated notSaved'));
Dan 关于为什么 setState 异步?
的详细解释:https://github.com/facebook/react/issues/11527#issuecomment-360199710
Detailed explanation by Dan on why is setState asynchronous?
: https://github.com/facebook/react/issues/11527#issuecomment-360199710
这篇关于反应,this.setState 不更新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!