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 摘要。