reactjs / reactjs/react.dev

setState() callback function: potential confusion of call order

オープン
#691 コメント 0 件 リアクション 2 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
JavaScript
スター
11.8k
フォーク
7.9k
平均マージ
1日 11時間
マージ済み PR(30日)
11

説明

This paragraph from the React.Component reference page:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

can create the impression that instead of doing:

this.setState({ value: 5 });
console.log(this.state.value); // => not necessarily 5

you can use the callback function to safely read the state back:

this.setState({ value: 5 }, () => console.log(this.state.value)); // => "guaranteed" 5

(especially if you draw a parallel between the callback function and the updater function)

and it may actually work in some cases where there's no setState batching, but as more calls get batched in the future, these constructs may generate unintended side-effects.

Instead, we could clarify that all callback functions for a batch of setState() calls get called after the entire batch has been processed.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Issue でリンクされている React.Component リファレンスページの setState セクションから始めてください。callback と batching に関する説明を見直し、callback の実行タイミングと batch 後に利用できる state が明確になるように更新してください。完了の条件は、例から callback が自分自身の個別の更新だけを確認するように読み取れないことです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript, react
領域
documentation
issue の種類
ドキュメント
難易度
2/5
見積もり時間
1〜3時間
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。