知海

规则:globals

ReactAPI 参考:ESLint 插件

globals

验证渲染期间对全局变量的赋值/修改,这是确保副作用必须在渲染之外运行的一部分。

规则详情 {/rule-details/}

全局变量存在于 React 的控制之外。当你在渲染期间修改它们时,就破坏了 React 关于渲染是纯函数的假设。这会导致组件在开发和生产环境中的行为不同、破坏 Fast Refresh,并使应用无法通过 React Compiler 等功能进行优化。

无效用法 {/invalid/}

本规则的错误代码示例:

js 复制代码
// ❌ Global counter
let renderCount = 0;
function Component() {
  renderCount++; // Mutating global
  return <div>Count: {renderCount}</div>;
}

// ❌ Modifying window properties
function Component({userId}) {
  window.currentUser = userId; // Global mutation
  return <div>User: {userId}</div>;
}

// ❌ Global array push
const events = [];
function Component({event}) {
  events.push(event); // Mutating global array
  return <div>Events: {events.length}</div>;
}

// ❌ Cache manipulation
const cache = {};
function Component({id}) {
  if (!cache[id]) {
    cache[id] = fetchData(id); // Modifying cache during render
  }
  return <div>{cache[id]}</div>;
}

有效用法 {/valid/}

本规则的正确代码示例:

js 复制代码
// ✅ Use state for counters
function Component() {
  const [clickCount, setClickCount] = useState(0);

  const handleClick = () => {
    setClickCount(c => c + 1);
  };

  return (
    <button onClick={handleClick}>
      Clicked: {clickCount} times
    </button>
  );
}

// ✅ Use context for global values
function Component() {
  const user = useContext(UserContext);
  return <div>User: {user.id}</div>;
}

// ✅ Synchronize external state with React
function Component({title}) {
  useEffect(() => {
    document.title = title; // OK in effect
  }, [title]);

  return <div>Page: {title}</div>;
}

帮助我们改进文档

发现翻译问题或内容错误?请告诉我们。