getDerivedStateFromProps是否实际上会更新状态?

时间:2019-03-05 18:32:23

标签: reactjs getderivedstatefromprops

我已经阅读了reactjs.org上有关getDerivedStateFromProps的文档。我已经看到了用例。而且我知道为什么要使用它。

但是我无法弄清楚它如何处理返回值。因此,我的问题是,它何时返回...它会去哪里?

它没有setState,因为它没有访问权限。

要设置状态,需要使用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上设置State。但这似乎与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的收益在什么时候起作用?

已更新:如果如上所述正确配置,则此生命周期方法实际上将更新状态。您不需要其他方法来设置状态

2 个答案:

答案 0 :(得分:1)

父组件重新渲染时,它会返回到状态。

答案 1 :(得分:1)

返回值在概念上类似于setState:

return { havingFun: nextProps.havingFun };

您可以在其中假设havingFun是状态属性,而值nextProps.havingFun是更新后的值。

使用return null意味着您对状态不做任何事情。

注意:getDerivedStateFromProps与setState的概念确实不同,尽管我在这里仅尝试以这种方式进行解释。

您应该阅读docs以获得更多详细信息:

  

getDerivedStateFromProps会在调用render方法之前(无论是在初始安装还是在后续更新中)都被调用。它应该返回一个对象以更新状态,或者返回null则不更新任何内容。

相关问题