React setState not updating state

冷暖自知 提交于 2019-11-26 12:22:47

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

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

setState() takes time to mutate the value and you javascript 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)

Using async/await

async changeHandler(event) {
    await this.setState({ yourName: event.target.value });
    console.log(this.state.yourName);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!