reactjs / reactjs/react.dev

Questionable Comment in the `useEvent` Example

未关闭
#5,280 0 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
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. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 issue 中链接的“Separating Events from Effects”示例开始,并将关于 useEvent 稳定性的说法与所示的 numberOfItems 和 url 值进行比较。完成的标准是文档明确说明延迟 callback 观察到哪些值,并解释为什么可以将事件函数从依赖项中省略。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, react
领域
documentation
Issue 类型
文档
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
需要澄清
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。