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?
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).
Note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop.
you can use getDerivedStateFromProps or componentDidMount, there is sequence to running lifecycles :