【问题标题】:Does getDerivedStateFromProps actually update state?getDerivedStateFromProps 真的会更新状态吗?
【发布时间】: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


    【解决方案1】:

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

    return { havingFun: nextProps.havingFun };
    

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

    当你使用return null 时,这意味着你没有对状态做任何事情。

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

    您应该阅读docs 了解更多详情:

    getDerivedStateFromProps 在调用 render 方法之前被调用,无论是在初始挂载时还是在后续更新时。它应该返回一个对象来更新状态,或者返回 null 以不更新任何内容。

    【讨论】:

    • 好的,所以它确实更新了状态。措辞有点令人困惑,因为它说它返回一个对象以更新状态,但没有传达该状态实际上是用该对象更新的。谢谢!
    【解决方案2】:

    父组件重新渲染时返回状态

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      相关资源
      最近更新 更多