React setState not updating state

前端 未结 9 654
慢半拍i
慢半拍i 2020-11-22 05:41

So I have this:

let total = newDealersDeckTotal.reduce(function(a, b) {
  return a + b;
},
0);

console.log(total, \'t         


        
9条回答
  •  长发绾君心
    2020-11-22 05:54

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

提交回复
热议问题