React setState不更新状态 [英] React setState not updating state

查看:195
本文介绍了React setState不更新状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个:

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 没有给出正确的总数但是总计呢?我甚至提出了超时延迟,看看是否解决了这个问题。
是否明显或者我应该发布更多代码?

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');
}); 

这篇关于React setState不更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆