How to migrate to new React lifecycle API?

2019-08-29 06:23发布

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?

2条回答
相关推荐>>
2楼-- · 2019-08-29 06:54

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-08-29 07:04

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

  1. getDerivedStateFromProps
  2. shouldComponentUpdate
  3. render
  4. getSnapshotBeforeUpdate
  5. componentDidUpdate
查看更多
登录 后发表回答