通过检查它们是否调用已知的非纯函数来验证 组件/钩子是纯函数。
¥Validates that components/hooks are pure by checking that they do not call known-impure functions.
规则详情
¥Rule Details
React 组件必须是纯函数 - 给定相同的属性,它们应该始终返回相同的 JSX。当组件在渲染过程中使用 Math.random()
或 Date.now()
之类的函数时,它们每次都会产生不同的输出,这违反了 React 的假设,并会导致诸如水合不匹配、记忆错误和不可预测的行为等错误。
¥React components must be pure functions - given the same props, they should always return the same JSX. When components use functions like Math.random()
or Date.now()
during render, they produce different output each time, breaking React’s assumptions and causing bugs like hydration mismatches, incorrect memoization, and unpredictable behavior.
常见违规
¥Common Violations
通常,任何对相同输入返回不同值的 API 都违反了此规则。常见示例包括:
¥In general, any API that returns a different value for the same inputs violates this rule. Usual examples include:
-
Math.random()
-
Date.now()
/new Date()
-
crypto.randomUUID()
-
performance.now()
无效
¥Invalid
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
// ❌ Math.random() in render
function Component() {
const id = Math.random(); // Different every render
return <div key={id}>Content</div>;
}
// ❌ Date.now() for values
function Component() {
const timestamp = Date.now(); // Changes every render
return <div>Created at: {timestamp}</div>;
}
有效
¥Valid
此规则的正确代码示例:
¥Examples of correct code for this rule:
// ✅ Stable IDs from initial state
function Component() {
const [id] = useState(() => crypto.randomUUID());
return <div key={id}>Content</div>;
}
故障排除
¥Troubleshooting
我需要显示当前时间
¥I need to show the current time
在渲染过程中调用 Date.now()
会使组件变得不纯:
¥Calling Date.now()
during render makes your component impure:
// ❌ Wrong: Time changes every render
function Clock() {
return <div>Current time: {Date.now()}</div>;
}
相反,将非纯函数移出渲染器:
¥Instead, move the impure function outside of render:
function Clock() {
const [time, setTime] = useState(() => Date.now());
useEffect(() => {
const interval = setInterval(() => {
setTime(Date.now());
}, 1000);
return () => clearInterval(interval);
}, []);
return <div>Current time: {time}</div>;
}