Why getDerivedStateFromProps is called after setState?

后端 未结 5 1607
别那么骄傲
别那么骄傲 2021-02-06 23:02

React introduced new static method getDerivedStateFromProps(props, state) which is called before every render method, but why? Calling it after prop change makes se

5条回答
  •  醉酒成梦
    2021-02-06 23:46

    The way getDerivedStateFromProps hook works whenever the new props, setState, and forceUpdate is being received.

    In the version of 16.3, React is not affecting getDerivedStateFromProps whenever the setState is being used. But they improved it in the version starting with 16.4, so whenever the setState is being called the getDerivedStateFromProps is being hooked.

    Here's extracted image from React lifecycle diagram:

    16.3

    ^16.4


    So, it's up to you when to hook the getDerivedStateFromProps by checking props and states properly. Here's an example:

    static getDerivedStateFromProps (props, state) {
      // check your condition when it should run?
      if(props.currentMonth != state.currentMonth) {
        return {
          currentMonth: state.currentMonth
        }
      }
      // otherwise, don't do anything
      else {
       return null
      }
    }
    

提交回复
热议问题