reactjs / reactjs/react.dev

[Hooks] - callbacks in useState hook examples

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

還沒有人認領這個 Issue。

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

描述

I would like to discuss about using callbacks to create new state which bases on current state in documentation for useState hook.
Current examples can be confusing for new developers which are not very familiar with js.
It would be easier for new developers to learn the rule like newer use value from this.state (for setState) or take current state value from scope (for hooks) to create new state. This simple rule leads to smaller amount of bugs.

So new developers can take this example from https://reactjs.org/docs/hooks-intro.html

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

and convert to something like this:

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
    setCount(count + 1);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>
        Click me
      </button>
    </div>
  );
}

with assumption that it will increment by 2 but it does not (it's based on observation with junior developers).

Shouldn't we change first example (and all 'counter' based examples in docs) to something like this?

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(currentValue => currentValue + 1)}>
        Click me
      </button>
    </div>
  );
}

and create new example to show 'standard' way to set state (example where new state is not based on current one).
Or maybe we should just say it's how JS (closures) works and left examples as is?
What's your opinion? I can create PR with changes but I'm not sure which path to choose. On the one hand it's how JS works but on the other hand I see it's confusing.

貢獻指南

開啟貢獻指南

從這裡開始

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

研究方向

https://reactjs.org/docs/hooks-intro.html 中的 useState 範例開始,並檢視文件中其他以計數器為基礎的範例。這個 issue 需要由 maintainer 決定要修改範例,還是說明現有行為;當選定的指引獲得一致的文件化時,即視為完成。

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

評估

技術堆疊
javascript, react
領域
documentation
Issue 類型
文件
難度
5/5
預估耗時
一週以上
活躍度
停滯
描述清晰度
需要釐清
新手友好度
32/100

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

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