Why getDerivedStateFromProps is called after setState?

后端 未结 5 1792
别那么骄傲
别那么骄傲 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:41

    For this case (updating the state based on props change), use:

    componentDidUpdate(prevProps) {
      // don't forget to compare props
      if (this.props.userID !== prevProps.userID) {
        this.fetchData(this.props.userID);
      }
    }
    

    componentDidUpdate will get called after each update (due to props changes / state changes). so you should check if the prop is changed (by this.props.userID !== prevProps.userID).

提交回复
热议问题