使用 getDerivedStateFromProps 生命周期方法时如何正确 return 更新状态?
How to properly return updated state when using getDerivedStateFromProps lifecycle method?
例如我们有这样的状态:
state = { hasSomething: true, anotherKey: '', ... }
我们应该只更新 'hasSomething':
static getDerivedStateFromProps(nextProps) {
if (nextProps.accessKey === 'admin') {
return {
hasSomething: false,
};
}
return null;
}
我们 return 新状态时是否需要销毁 prevState?
例如像这样:
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.accessKey === 'admin') {
return {
...prevState,
hasSomething: false,
};
}
return null;
}
或者我们不需要它?
我检查了 console.log(this.state),如果我不破坏 prevState,它 return 就是整个本地状态。
我在官方 React 文档中找不到此信息:(
P.S。这个逻辑只是一个例子:)
官方文档说 It should return an object to update the state, or null to update nothing.
(https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops). It is not cleared the state when you return only part of it, so it works like setState
(https://reactjs.org/docs/react-component.html#setstate)。 setState
文档说
You may optionally pass an object as the first argument to setState() instead of a function. This performs a shallow merge of stateChange into the new state.
,所以你不需要破坏之前的状态。
例如我们有这样的状态:
state = { hasSomething: true, anotherKey: '', ... }
我们应该只更新 'hasSomething':
static getDerivedStateFromProps(nextProps) {
if (nextProps.accessKey === 'admin') {
return {
hasSomething: false,
};
}
return null;
}
我们 return 新状态时是否需要销毁 prevState? 例如像这样:
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.accessKey === 'admin') {
return {
...prevState,
hasSomething: false,
};
}
return null;
}
或者我们不需要它? 我检查了 console.log(this.state),如果我不破坏 prevState,它 return 就是整个本地状态。
我在官方 React 文档中找不到此信息:(
P.S。这个逻辑只是一个例子:)
官方文档说 It should return an object to update the state, or null to update nothing.
(https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops). It is not cleared the state when you return only part of it, so it works like setState
(https://reactjs.org/docs/react-component.html#setstate)。 setState
文档说
You may optionally pass an object as the first argument to setState() instead of a function. This performs a shallow merge of stateChange into the new state.
,所以你不需要破坏之前的状态。