何时使用React setState回调

当反应组件状态改变时,将调用render方法。因此,对于任何状态更改,都可以在渲染方法主体中执行操作。那么setState回调是否有特定的用例?

路易卡卡西2020/03/11 11:41:26

考虑setState调用

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

理念

setState可以在异步函数中调用

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

老丝村村2020/03/11 11:41:26

我想到的1.用例是一个api调用,不应进入渲染,因为它将用于each状态更改。而且,API调用仅应在特殊的状态更改上执行,而不应在每个渲染上执行。

changeSearchParams = (params) => {
  this.setState({ params }, this.performSearch)
} 

performSearch = () => {
  API.search(this.state.params, (result) => {
    this.setState({ result })
  });
}

因此,对于任何状态更改,都可以在渲染方法主体中执行操作。

非常糟糕的做法,因为render-method应该是纯净的,这意味着不应执行任何操作,状态更改,api调用,只需合并视图并返回即可。仅应在某些事件上执行操作。渲染不是事件,而是componentDidMount例如。