reactjs / reactjs/react.dev

Prefer functional updates version in hooks documentation

未關閉
#1,967 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

主要語言
JavaScript
星號
11.8k
分支
7.9k
平均合併
1 天 11 小時
30 天內合併 PR
11

描述

Currently React hooks documentation at section Updating state is using a counter example for bot hooks and class based components. To recap:

In a class, we need to call this.setState() to update the count state:

  <button onClick={() => this.setState({ count: this.state.count + 1 })}>
    Click me
  </button>

In a function, we already have setCount and count as variables so we don’t need this:

  <button onClick={() => setCount(count + 1)}>
    Click me
  </button>

Although I can understand than this documentation must be simple and this example is really straightforward, isn't this a bad patter? Modifying state with a value based on old state?

The Functional update version is documented few pages after this example.

I'm wondering if:

  • this example must be changed (although is probably the best type of example for state), or
  • a warning box should be added to warn the user this is not the correct way to do.

To be more clear: I know there's nothing wrong with this specific example, but newcomers can quickly try to do something like calling setCount(count + 1) multiple times.

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

從 hooks-state.html 中的 Updating state 部分開始,將其中的計數器範例與 hooks-reference.html 中的 Functional updates 部分進行比較。判斷範例或說明性警告哪一種更能處理基於先前 state 的重複更新;當文件能在不與現有範例矛盾的情況下清楚地引導新手時,即表示完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
javascript, react
領域
documentation
Issue 類型
文件
難度
2/5
預估耗時
1-3 小時
活躍度
停滯
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。