Can getDerivedStateFromProps be used as an alternative to componentWillReceiveProps

后端 未结 1 1760
说谎
说谎 2020-11-29 11:36

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

This is what the 16.3 doc says.

相关标签:
1条回答
  • 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.

    0 讨论(0)
提交回复
热议问题