React setState best practice

When the new state reply on current state, please do not simply use it like this:

this.setState({counter: this.state.counter + 1}) // do not do this because setState is async, there may exist conflict issue

Because setState is executed asynchronously, there may exist conflct issue as two operation is doing on the same state at the same time. 

The best way to solve this is:

this.setState(
     (prevState, props) => {
           return {
                 counter: prevState.counter + 1
           }
     }   
)

In this way, the operation will lock the prevState untill the operation is finished

猜你喜欢

转载自www.cnblogs.com/openzig/p/9403959.html