反应 setState 不更新状态 [英] React setState not updating state
问题描述
所以我有这个:
let total = newDealersDeckTotal.reduce(function(a, b) {
return a + b;
},
0);
console.log(total, 'tittal'); //outputs correct total
setTimeout(() => {
this.setState({ dealersOverallTotal: total });
}, 10);
console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1'); //outputs incorrect total
newDealersDeckTotal
只是一个数字数组 [1, 5, 9]
例如但是 this.state.dealersOverallTotal
没有给出正确的总数,但 total
有吗?我什至设置了超时延迟,看看这是否解决了问题.任何明显的还是我应该发布更多代码?
newDealersDeckTotal
is just an array of numbers [1, 5, 9]
e.g.
however this.state.dealersOverallTotal
does not give the correct total but total
does? I even put in a timeout delay to see if this solved the problem.
any obvious or should I post more code?
推荐答案
setState()
通常是异步的,这意味着你在 console.log
时的状态,还没更新.尝试将日志放入 setState()
方法的回调中.状态改变完成后执行:
setState()
is usually asynchronous, which means that at the time you console.log
the state, it's not updated yet. Try putting the log in the callback of the setState()
method. It is executed after the state change is complete:
this.setState({ dealersOverallTotal: total }, () => {
console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1');
});
这篇关于反应 setState 不更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!