React setState not updating state

前端 未结 9 647
慢半拍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: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() {
         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.

提交回复
热议问题