React setState not updating state

前端 未结 9 875
慢半拍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 06:11

    The setState() operation is asynchronous and hence your console.log() will be executed before the setState() mutates the values and hence you see the result.

    To solve it, log the value in the callback function of setState(), like:

    setTimeout(() => {
        this.setState({dealersOverallTotal: total},
        function(){
           console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1');
        });
    }, 10)
    

提交回复
热议问题