React setState not updating state

前端 未结 9 641
慢半拍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)
    
    0 讨论(0)
  • 2020-11-22 06:16

    setState is asynchronous. You can use callback method to get updated state.

    changeHandler(event) {
        this.setState({ yourName: event.target.value }, () => 
        console.log(this.state.yourName));
     }
    
    0 讨论(0)
  • 2020-11-22 06:21

    I had the same situation with some convoluted code, and nothing from the existing suggestions worked for me.

    My problem was that setState was happening from callback func, issued by one of the components. And my suspicious is that the call was occurring synchronously, which prevented setState from setting state at all.

    Simply put I have something like this:

    render() {
        <Control
            ref={_ => this.control = _}
            onChange={this.handleChange}
            onUpdated={this.handleUpdate} />
    }
    
    handleChange() {
        this.control.doUpdate();
    }
    
    handleUpdate() {
        this.setState({...});
    }
    

    The way I had to "fix" it was to put doUpdate() into setTimeout like this:

    handleChange() {
        setTimeout(() => { this.control.doUpdate(); }, 10);
    }
    

    Not ideal, but otherwise it would be a significant refactoring.

    0 讨论(0)
提交回复
热议问题