问题描述
getDerivedStateFromProps 被添加为旧组件WillReceiveProps 的更安全替代方案.
这就是 16.3 文档所说的.这个生命周期还有什么其他的吗,还是只是改名了?
This is what the 16.3 doc says. Is there anything more to this lifecycle or is it just a name change?
推荐答案
getDerivedStateFromProps
不仅仅是对 componentWillReceiveProps
的名称更改.它是一个静态方法,在组件实例化之后或接收新 props 之前调用,与 componentWillReceiveProps
不同,它在初始渲染时未调用.
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.
返回一个对象来更新状态以响应 prop 的变化.
返回 null 表示状态没有改变.
Return null to indicate no change to state.
引入了静态生命周期方法以防止对实例属性的不安全访问.
Static lifecycle methods are introduced to prevent unsafe access of instance properties.
getDerivedStateFromProps
的目的是仅根据 props 变化更新状态,而不是根据 prevProps
执行 API 调用或函数调用等可以完成的操作.所有这些都可以在 componentDidUpdate
生命周期函数中完成,这是安全的,因为即使更改是在 componentWillReceiveProps
中完成的,数据也会在渲染后到达,而且大多数情况下你会触发另一个重新渲染,这可以在 componentDidUpdate
生命周期方法中很好地完成.
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.
你可以参考这个RFC 以详细了解进行此更改的原因.
You can refer to this RFC to understand more about why this change was made.
这篇关于可以使用 getDerivedStateFromProps 作为 componentWillReceiveProps 的替代方案吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!