Skip to content

错误: 也许多 re-渲染. React 限制数字的 渲染到 prevent 无限循环

错误信息

                也许多 re-渲染. React 限制数字的 渲染到 prevent 无限循环.
              

快速摘要

你 called 状态 setter 函数 directly in 组件请求体 (不 in 事件处理函数 or 副作用), causing 无限渲染循环.

为什么发生

  • Called setState directly in 组件请求体

  • Called setState in 函数那个运行 on 每个渲染

  • Used setter as 默认值 for another useState

最小示例

✗ 错误代码
function Component() {
  const [count, setCount] = useState(0);
  setCount(count + 1); // Called every render!
  return <div>{count}</div>;
}
✓ 修复代码
function Component() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Calling setCount 期间渲染触发 re-渲染, 哪个 calls setCount 再次 — 无限循环. Moving 它到 onClick breaks cycle.

如何诊断

  • Look for setState calls 之外事件处理函数 and useEffect

  • 检查如果 setter 是 called 期间每个渲染

如何修复

  • Move setState call 到事件处理函数

  • Move setState call 到 useEffect 使用 proper dependencies

  • Use lazy initializer 如果 computing 初始状态: useState(() => compute())

如何预防

  • 从不 call setState in 渲染请求体

  • Use lazy initializers for expensive 初始状态 computations

相关资源

相关术语

相关课程

  • 状态

    学习到 avoid 无限渲染循环.

← 返回语言