
规则:static-components
ReactAPI 参考:ESLint 插件
规则:static-components
校验组件是静态的,而不是每次渲染时重新创建。动态重新创建的组件会重置 state 并触发过度重新渲染。
规则详情
在其它组件内部定义的组件会在每次渲染时重新创建。React 将每个都视为全新的组件类型,卸载旧组件并挂载新组件,在此过程中销毁所有 state 和 DOM 节点。
无效
此规则的不正确代码示例:
js
// ❌ Component defined inside component
function Parent() {
const ChildComponent = () => { // New component every render!
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
};
return <ChildComponent />; // State resets every render
}
// ❌ Dynamic component creation
function Parent({type}) {
const Component = type === 'button'
? () => <button>Click</button>
: () => <div>Text</div>;
return <Component />;
}
有效
此规则的正确代码示例:
js
// ✅ Components at module level
const ButtonComponent = () => <button>Click</button>;
const TextComponent = () => <div>Text</div>;
function Parent({type}) {
const Component = type === 'button'
? ButtonComponent // Reference existing component
: TextComponent;
return <Component />;
}
故障排查
我需要有条件地渲染不同组件
你可能会在组件内部定义组件以访问局部 state:
-
js
// ❌ Wrong: Inner component to access parent state
function Parent() {
const [theme, setTheme] = useState('light');
function ThemedButton() { // Recreated every render!
return (
<button className={theme}>
Click me
</button>
);
}
return <ThemedButton />;
}
改为通过 props 传递数据:
js
// ✅ Better: Pass props to static component
function ThemedButton({theme}) {
return (
<button className={theme}>
Click me
</button>
);
}
function Parent() {
const [theme, setTheme] = useState('light');
return <ThemedButton theme={theme} />;
}
注意:
如果你发现自己想在其它组件内部定义组件以访问局部变量,这说明你应该传递 props。这会使组件更可复用和可测试。
帮助我们改进文档
发现翻译问题或内容错误?请告诉我们。
