reactjs / reactjs/react.dev

`state` property must be defined if `getDerivedStateFromProps` is used

未关闭
#796 3 条评论 10 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
11

描述

It seems that if getDerivedStateFromProps is defined, the component must also initialize its state property. That requirement is undocumented.

The following react component will generate a warning: "MyComponent: Did not properly initialize state during construction. Expected state to be an object, but it was undefined."

class MyComponent extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    return null;
  }
  render() {
    return <span>Foo</span>
  }
}

The warning can be resolved by adding state = {} either in the class definition or the constructor, or by not using getDerivedStateFromProps.

I found this warning confusing:

  • since I'm not overriding the constructor, it's not obvious I'm responsible for initializing state for the construction to work correctly.
  • I can use this.setState without ever having initialized state without warning, so I don't have prior expectations initializing state would be required to use it.
  • Since the only state handling logic for this component comes from getDerivedStateFromProps, I confused the warning with saying that getDerivedStateFromProps was returning undefined.
  • There isn't any documentation in getDerivedStateFromProps or in "State and Lifecycle" that this initialization is required if that lifecycle method is used

I don't know if this is best resolved by making the warning clearer, or documenting the requirement for state initialization either in the docs for getDerivedStateFromProps or in "State and Lifecycle". In hindsight, the warning (while perhaps a little succinct) does indicate what the problem is; it's just that the solution is non-obvious. So I figured I'd open this as a docs issue here.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 getDerivedStateFromProps 文档以及 issue 中提到的“State and Lifecycle”部分开始。确认其中如何描述 state 初始化,然后明确使用此 lifecycle 的组件必须初始化 state;当相关指南中记录了该要求和解决方案时即完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, react
领域
documentation
Issue 类型
文档
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。