react组件如何销毁
组件销毁的触发条件
React组件的销毁通常由以下条件触发:父组件不再渲染该子组件、路由切换导致组件卸载、条件渲染中条件不满足。销毁时React会自动调用生命周期方法并清理相关资源。
类组件中的销毁处理
在类组件中,通过实现componentWillUnmount生命周期方法执行清理逻辑。常见的清理操作包括取消网络请求、清除定时器、移除事件监听等。
class ExampleComponent extends React.Component {
componentDidMount() {
this.timer = setInterval(() => console.log('Tick'), 1000);
}
componentWillUnmount() {
clearInterval(this.timer); // 清除定时器
console.log('Component will unmount');
}
render() {
return <div>Example Content</div>;
}
}
函数组件中的销毁处理
函数组件通过useEffect钩子的清理函数实现销毁逻辑。返回的函数会在组件卸载时自动执行。
import React, { useEffect } from 'react';
function ExampleComponent() {
useEffect(() => {
const timer = setInterval(() => console.log('Tick'), 1000);
return () => {
clearInterval(timer); // 清理函数
console.log('Cleanup on unmount');
};
}, []);
return <div>Example Content</div>;
}
手动触发组件销毁
通过条件渲染或状态控制实现手动销毁。父组件可通过移除子组件或改变渲染条件触发子组件销毁。
function ParentComponent() {
const [showChild, setShowChild] = React.useState(true);
return (
<div>
<button onClick={() => setShowChild(false)}>Unmount Child</button>
{showChild && <ChildComponent />}
</div>
);
}
注意事项
- 避免在已销毁的组件上执行
setState操作,可通过标志变量或_isMounted模式防止内存泄漏。 - 清理异步操作时,使用
AbortController取消Fetch请求或手动终止Promise链。 - 第三方库(如D3、Three.js)创建的实例需在销毁时手动释放资源。







