何时使用React setState回调

reactjs React.js

神无Green前端

2020-03-11

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

第607篇《何时使用React setState回调》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
路易卡卡西 2020.03.11

考虑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

我想到的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例如。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android