所以我有这个:
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呢?我什至设置了超时延迟,以查看是否可以解决问题。任何明显的还是我应该发布更多代码?
[1, 5, 9]
this.state.dealersOverallTotal
total
setState()通常是异步的,这意味着在您console.log处于状态时,它尚未更新。尝试将日志放入setState()方法的回调中。状态更改完成后执行:
setState()
console.log
this.setState({ dealersOverallTotal: total }, () => { console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1'); });