(1) Background

React setState method is executed asynchronously in react. How to use setState value in our code will be presented in this article.

(2) Specific solutions

//1. Set the code this.setState({myState:'doubi'
   }, function() {this.stateFunction()}) //2. Call directly from a functionstateFunction() {
   console.log('doubi', this.state.myState)
}Copy the code

The react setstate method uses the second argument to call the callback function, so we don’t need to write a callback function.

this.setState({
    myState: 'doubi'
    },() => {  
    console.log(111);
})Copy the code

(3) Pay attention to problems

1. The stateFunction() function called in setState is not executed immediately, but only when it is called. That is, function in setState is declared to be used immediately, not executed immediately.

2. When the stateFunction() function is passed in as an argument, the setState function is also required.