验证组件是否为静态,而不是每次渲染都重新创建。动态重新创建的组件可能会重置状态并触发过多的重新渲染。
¥Validates that components are static, not recreated every render. Components that are recreated dynamically can reset state and trigger excessive re-rendering.
规则详情
¥Rule Details
在其他组件中定义的组件会在每次渲染时重新创建。React 将每个组件视为一个全新的组件类型,卸载旧组件并挂载新组件,在此过程中销毁所有状态和 DOM 节点。
¥Components defined inside other components are recreated on every render. React sees each as a brand new component type, unmounting the old one and mounting the new one, destroying all state and DOM nodes in the process.
无效
¥Invalid
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
// ❌ 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 />;
}
有效
¥Valid
此规则的正确代码示例:
¥Examples of correct code for this rule:
// ✅ 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 />;
}
故障排除
¥Troubleshooting
我需要有条件地渲染不同的组件
¥I need to render different components conditionally
你可能在内部定义组件来访问本地状态:
¥You might define components inside to access local state:
// ❌ 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 />;
}
改为将数据作为属性传递:
¥Pass data as props instead:
// ✅ 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} />;
}