reactjs / reactjs/react.dev

Questionable Comment in the `useEvent` Example

オープン
#5,280 コメント 0 件 リアクション 1 件 担当者 0 名 GitHub で見る

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

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

説明

I found a paragraph from Separating Events from Effects in the beta React Docs, which I couldn't wrap my head around:

In this example, url inside onVisit corresponds to the latest url (which could have already changed), but visitedUrl corresponds to the url that originally caused this Effect (and this onVisit call) to run.

The mentioned example is effectively the one below:

function Page({ url }) {
  const { items } = useContext(ShoppingCartContext);
  const numberOfItems = items.length;

  const onVisit = useEvent(visitedUrl => {
    // `url` captured here is claimed to be the latest, not the original
    // but what about `numberOfItems`?
    logVisit(visitedUrl, numberOfItems);
  });

  // intend to log the `url` that originally caused this Effect, 
  // along with the original `numberOfItems`.
  useEffect(() => {
    setTimeout(() => {
      onVisit(url);
    }, 5000); // Delay logging visits
  }, [url]);

  // ...
}

More essentially, I believe my confusion stems from the claims below:

This solves the problem. Similar to the set functions returned from useState, all Event functions are stable: they never change on a re-render. This is why you can skip them in the dependency list. They are not reactive.

How can Event functions like onVisit are stable, when they need to capture the relevant reactive values like numberOfItems?

Are they stable, but have access to the freshly-constructed anonymous function, which captures the relevant reactive values?

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

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

はじめの一歩

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

調査の方向性

issue にリンクされている「Separating Events from Effects」の例から始め、useEvent の安定性に関する主張と、示されている numberOfItems および url の値を比較してください。遅延された callback がどの値を監視するのかをドキュメントで明確に解決し、なぜイベント関数を依存関係から省略できるのかを説明できれば完了です。

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

評価

技術スタック
javascript, react
領域
documentation
issue の種類
ドキュメント
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

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

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