reactjs - getDerivedStateFromProps 是否真的更新状态?

标签 reactjs getderivedstatefromprops

我已经阅读了reactjs.org上有关getDerivedStateFromProps的文档。我看过用例。我明白为什么要使用它。

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

它不会设置State,因为它无权访问它。

要设置状态,需要使用 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 的返回值在什么时候发挥作用?

更新:如果按上述正确配置,此生命周期方法实际上将更新状态。您不需要额外的方法来设置状态

最佳答案

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

return { havingFun: nextProps.havingFun };

您可以假设 havingFun 是一个状态属性,并且值 nextProps.havingFun 是更新值。

当您使用return null时,意味着您没有对状态执行任何操作。

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

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

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

关于reactjs - getDerivedStateFromProps 是否真的更新状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55009374/

相关文章:

javascript - getDerivedStateFromProps 返回未定义

reactjs - 使用 getDerivedStateFromProps 返回一个或两个对象?

javascript - react 重定向并将信息传输到另一个页面

javascript - React Hooks 真的不支持 async setState 吗?

javascript - 使用 getDerivedStateFromProps (React) 时出现错误 : Cannot read property 'setState' of null

reactjs - 为什么 getDerivedStateFromProps 在 setState 之后调用?

javascript - 使用 redux 更新状态时,react 中的推送工作

javascript - 将一个对象分配给另一个不带所有字段的对象

javascript - 在 React 状态下使用嵌套对象