reactjs / reactjs/react.dev

Inconsistent usage of `.useState` in "Using the State Hook" article

未關閉
#3,351 0 則留言 4 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

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

描述

Hello! 👋

This is my first contribution to the React Documentation, and I first wanted to say how much I love the documentation. I find the language style used throughout it to be simple, accessible, and therefore easy to follow.

As I was going through the documentation this weekend, I made my way from State and Lifecycle to Using the State Hook. In the former article, I noted the following piece of information, which I thought was an important detail about updating state.

https://github.com/reactjs/reactjs.org/blob/6682068641c16df6547b3fcdb7877e71bb0bebf9/content/docs/state-and-lifecycle.md#L341-L345

Meanwhile, in the "Component Class Equivalent" section in the latter document, I noticed this code example did not use a function to update state using the previous state value.

https://github.com/reactjs/reactjs.org/blob/6682068641c16df6547b3fcdb7877e71bb0bebf9/content/docs/hooks-state.md#L37-L57

I found this confusing. The point above about accommodating a possibly asynchronous state update seemed critical to ensure deterministic behaviour. I was surprised to see the code here (and throughout other parts of this article) not using a function to update the state value synchronously.

There may be a few reasons why this was done in my mind.

  • The example is small/trivial enough that using a function versus a direct update does not make a major difference.
  • This is a minor implementation detail not relevant to the usage of the state hook.

It's also possible I may have just misunderstood this example. I believe though that is not only inconsistent, but also makes the function component and class component inequivalent, because the original is completely synchronous, whereas the latter contains some potentially asynchronous behaviour.

Of course this is easily fixed by converting a line like

this.setState({ count: this.state.count + 1 })

to

this.setState((state) => ({ count: state.count + 1 })

I'm writing this first and foremost with the intention to clear up confusion that I experienced, and that others may as well. But I also want to ensure that my thinking is correct here!

貢獻指南

開啟貢獻指南

從這裡開始

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

研究方向

首先比較 content/docs/state-and-lifecycle.md 和 content/docs/hooks-state.md 中的範例,特別是關於更新狀態和 Component Class Equivalent 的連結章節。檢查範例是否應使用函式式更新,或解釋其中的差異,然後更新文章,使這種關係和行為清楚且一致。

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

評估

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

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

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