reactjs / reactjs/react.dev

Explanation on what can go wrong if Hooks were called inside loops or nested functions?

未关闭
#2,492 2 条评论 3 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
11

描述

The Rules of Hooks section states that the first rule of Hooks is to only call hooks at the top level, i.e. "Don’t call Hooks inside loops, conditions, or nested functions". Later in the section, it explains what happens if we put a Hook call inside a condition. This still leaves me with some questions/doubts though. Are there examples where something can go wrong if Hooks were:

  • called inside a loop?
  • called inside a nested function? Furthermore, isn't a custom hook just a nested function? 🤔

I've tried to dig into some related questions on Stack Overflow here and here, but the answers provided only give the correct examples, but not the incorrect ones.

Could you provide incorrect examples for the other two cases? Or at least a little bit clarification would be most appreciated. :)

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 Rules of Hooks 部分开始,尤其是现有的关于有条件调用 Hook 的说明。添加涵盖循环和嵌套函数中的 Hooks 的错误示例或澄清,包括 custom Hooks 有何不同,并在文档清楚解释这些情况后将工作视为完成。

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

评估

技术栈
javascript, react
领域
documentation
Issue 类型
文档
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

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