Is it OK to call setState from within shouldComponentUpdate?

前端 未结 2 2002
眼角桃花
眼角桃花 2021-02-07 13:35

In response to a state change, I want to trigger another state change. Is that inherently a bad idea?

The specific sort of scenario is that the component is modeled as a

相关标签:
2条回答
  • 2021-02-07 13:58

    No. Please use componentWillReceiveProps instead. It has the same signature of shouldComponentUpdate and you're safe to call this.setState there.

    0 讨论(0)
  • 2021-02-07 14:19

    shouldComponentUpdate is intended specifically to determine if the component should update at all. To do things like:

    if (nextState.counter == this.state.counter && nextProps.foo == this.Props.foo) {
      return false;
    }
    

    componentWillReceiveProps is for responding to external (props) changes. There is no equivalent componentWillReceiveState, as pointed out in the docs. Your component (and only your component) triggers it own state changes, usually through one or more of the following events:

    • initial rendering in getInitialState
    • updated props in componentWillReceiveProps
    • user interaction in <input> fields etc, e.g. in custom onChangeInput() functions in your component.
    • in flux: responding to store changes from listeners, typically in custom functions calling getStateFromStores(), where state is updated.

    I guess it doesn't make sense to have one function inside a component to create a state change, and then another function inside the same component to intervene before state is updated..

    In your case, you could move the logic (to determine if state needs to be updated) to a getStateFromStores() function where you handle store updates.
    Or, you could simply leave it in state, and change your render function, so that it renders differently if counter > 4.

    0 讨论(0)
提交回复
热议问题