When to use React setState callback

前端 未结 4 1683
悲哀的现实
悲哀的现实 2020-11-22 00:03

When a react component state changes, the render method is called. Hence for any state change, an action can be performed in the render methods body. Is there a particular u

4条回答
  •  粉色の甜心
    2020-11-22 00:34

    Consider setState call

    this.setState({ counter: this.state.counter + 1 })
    

    IDEA

    setState may be called in async function

    So you cannot rely on this. If the above call was made inside a async function this will refer to state of component at that point of time but we expected this to refer to property inside state at time setState calling or beginning of async task. And as task was async call thus that property may have changed in time being. Thus it is unreliable to use this keyword to refer to some property of state thus we use callback function whose arguments are previousState and props which means when async task was done and it was time to update state using setState call prevState will refer to state now when setState has not started yet. Ensuring reliability that nextState would not be corrupted.

    Wrong Code: would lead to corruption of data

    this.setState(
       {counter:this.state.counter+1}
     );
    

    Correct Code with setState having call back function:

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

    Thus whenever we need to update our current state to next state based on value possed by property just now and all this is happening in async fashion it is good idea to use setState as callback function.

    I have tried to explain it in codepen here CODE PEN

提交回复
热议问题