Skip to content

Dependency 数组

一句话解释

dependency 数组是 其次实参到 useEffect/useMemo/useCallback 那个 tells React 当到 re-运行 or recompute.

用大白话说

dependency 数组 controls 当 Hook re-运行. 它's 其次实参到 useEffect, useMemo, and useCallback — an array of values that the Hook depends on.

  • [] — run once on mount (for effects) / compute once (for memo). The empty array means "否 dependencies, 从不 re-运行."
  • [值] — run on mount and whenever 值 changes.
  • [, b] — run on mount and whenever ` or b` changes.
  • Omitted — run after every render (effects only; useMemo/useCallback require a deps array).

Getting the dependency array right is critical. If you omit a dependency that the effect uses, you get stale closures (the effect uses old values). If you include too many, the effect runs more than necessary. The eslint-plugin-react-Hook exhaustive-deps rule catches these issues automatically.

示例

jsx
useEffect(() => {
  document.title = `Hello, ${name}`;
}, [name]); // re-run only when name changes

useEffect(() => {
  console.log("Mounted!");
}, []); // run once on mount

首先副作用 re-运行 whenever name 更改. 其次运行仅 一次因为 dependency 数组是 空.

常见混淆

  • 容易混淆的对象: 空数组

    关键区别: 空 dependency 数组 [] 平均值 '运行一次 on mount.' Omitting 数组完全平均值 '运行之后每个渲染.' 这些是 very 不同 — omitting 它是 很少什么你 想要.

相关术语

相关资源

相关课程

  • useEffect

    学习 dependency 数组 and 常见 pitfalls.

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表