在渲染期间验证对全局变量的赋值/修改,这是确保副作用必须在渲染之外执行的一部分。
🌐 Validates against assignment/mutation of globals during render, part of ensuring that side effects must run outside of render.
规则详情
🌐 Rule Details
全局变量存在于 React 的控制之外。当你在渲染过程中修改它们时,你就打破了 React 对渲染是纯函数的假设。这可能导致组件在开发环境和生产环境中的行为不同,破坏快速刷新,并使你的应用无法通过 React 编译器等功能进行优化。
🌐 Global variables exist outside React’s control. When you modify them during render, you break React’s assumption that rendering is pure. This can cause components to behave differently in development vs production, break Fast Refresh, and make your app impossible to optimize with features like React Compiler.
无效
🌐 Invalid
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
// ❌ 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
此规则的正确代码示例:
🌐 Examples of correct code for this rule:
// ✅ 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>;
}