【发布时间】:2019-03-05 18:32:23
【问题描述】:
我已阅读 reactjs.org 上有关 getDerivedStateFromProps 的文档。我看过用例。而且我明白为什么要使用它。
但我无法弄清楚它是如何处理返回值的。因此我的问题是,当它返回时......它会去哪里?
它没有设置状态,因为它无权访问它。
要设置状态,需要使用 componentDidUpdate 并查找更改,然后设置状态。
假设以下代码:
public static getDerivedStateFromProps: IArrowFunction = (nextProps: IMyContainerProps, prevState: IMyContainerState) => {
if (nextProps.havingFun !== prevState.havingFun) {
console.log('[MyContainer.tsx] getDerivedStateFromProps :::::CHANGED::::::', nextProps, prevState);
return { havingFun: nextProps.havingFun };
} else { return null; }
}
那么 React 对返回的 ^ 做了什么?
然后我可以在 componentDidMount 上设置状态。但这似乎与 getDerivedStateFromProps 没有任何关系。此外,此生命周期方法每次都会触发。它会强制重新渲染。
public componentDidUpdate(prevProps: IMyContainerProps, prevState: IMyContainerState): void {
if (prevState.havingFun !== this.props.havingFun) {
console.log('[MyContainer.tsx] componentDidUpdate *******CHANGED******', prevState, prevProps, this.props);
this.setState({ havingFun: this.props.havingFun });
}
}
getDerivedStateFromProps 的返回在什么时候起作用?
更新:如果如上正确配置,此生命周期方法实际上会更新状态。您不需要额外的方法来设置状态
【问题讨论】:
标签: reactjs getderivedstatefromprops