Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

reactjs - Can getDerivedStateFromProps be used as an alternative to componentWillReceiveProps

getDerivedStateFromProps is being added as a safer alternative to the legacy componentWillReceiveProps.

This is what the 16.3 doc says. Is there anything more to this lifecycle or is it just a name change?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...