getDerivedStateFromProps
is not just a name change to componentWillReceiveProps
. It's a static method that is called after a component is instantiated or before it receives new props, unlike componentWillReceiveProps
which was not called on initial render.
Return an object to update state in response to prop changes.
Return null to indicate no change to state.
Static lifecycle methods are introduced to prevent unsafe access of instance properties.
The purpose of getDerivedStateFromProps
is to only update the state based on props change and not take actions like API call or function call based on prevProps
that could be done. All of these could be done in the componentDidUpdate
lifecycle function which is safe because even if the change was done in componentWillReceiveProps
the data would arrive after render and most often you would trigger another re-render, which could well be done in the componentDidUpdate
lifecycle method.
You can refer to this RFC to understand more about why this change was made.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…