How to migrate to new React lifecycle API?

2019-08-29 06:57发布

问题:

As you know some lifecycle methods like componentWillReceiveProps are now deprecated.

Well, my code used this lifecycle method and now I have no idea how to migrate to the new API of React.

Here is how I used:

componentWillReceiveProps(nextProps) {
    if (nextProps.newPost) {
        this.props.posts.unshift(nextProps.newPost);
    }
}

In the react blog I could read that...

Together with componentDidUpdate, this new lifecycle should cover all use cases for the legacy componentWillReceiveProps.

... but how to implement this?

回答1:

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

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

Note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop.



回答2:

you can use getDerivedStateFromProps or componentDidMount, there is sequence to running lifecycles :

  1. getDerivedStateFromProps
  2. shouldComponentUpdate
  3. render
  4. getSnapshotBeforeUpdate
  5. componentDidUpdate