我正在尝试从 componentWillReceiveProps 转移到 getDerivedStateFromProps ,在某些情况下,我成功了,但是当案例将道具附加到现有状态时,事情开始变得不一样了。当对组件的状态进行更新时,状态会发生变化(并且组件在更新后会发生变化)但仍呈现之前的状态。使用 getDerivedStateFromProp 而不是 componentWillReceiveProps 时会发生一些奇怪的事情。似乎该方法不能很好地处理“内部”更改。在以下示例中,我在 Child 上设置了 getDerivedStateFromProp 并且它可以工作,但因为仅渲染道具。在一个更简单的示例中也观察到了这种行为,其中我没有任何子组件并且只是呈现状态更改。
下面的代码显示了一个子组件,用于打印/显示 props 接收的数据,同时使用删除数据处理程序(从子组件交互中删除存储在父级的数据)。使用时getDerivedStateFromProps()I can't access tothis.state和 prevState 并不意味着相同,因为状态是累积的。当我从子组件中删除数据时,不会更新子组件的道具(使用 componentWillReceiveProps 没问题)。所以,我找不到替代我的方法UNSAFE_componentWillReceiveProps
componentWillReceiveProps:
UNSAFE_componentWillReceiveProps(nextProps){
this.setState({
data: [...this.state.data,...nextProps.data]
})
}
Run Code Online (Sandbox Code Playgroud)
getDerivedStateFromProps:
static getDerivedStateFromProps(nextProps,state) {
if (!isEqual(nextProps.data, state.data)) {
return {
data: [...state.data, ...nextProps.data]
};
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
按预期工作的原始代码(在 Parent Comp 上的 getDerivedStateFromProps 之前)
DataConsole - 父组件:
export class DataConsole extends Component {
// Used for unsubscribing when our components unmount
unsub = null; …Run Code Online (Sandbox Code Playgroud)