When to use React setState callback

前端 未结 4 1648
悲哀的现实
悲哀的现实 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:28

    The 1. usecase which comes into my mind, is an api call, which should't go into the render, because it will run for each state change. And the API call should be only performed on special state change, and not on every render.

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

    Hence for any state change, an action can be performed in the render methods body.

    Very bad practice, because the render-method should be pure, it means no actions, state changes, api calls, should be performed, just composite your view and return it. Actions should be performed on some events only. Render is not an event, but componentDidMount for example.

提交回复
热议问题