react组件如何销毁
销毁 React 组件的常见方法
在 React 中,组件的销毁通常由 React 的声明式渲染机制自动处理。以下是几种常见场景和操作方式:
条件渲染触发销毁
通过条件判断控制组件的渲染,当条件为 false 时,React 会自动卸载并销毁组件:
{shouldRender && <MyComponent />}
路由切换导致销毁
使用 React Router 时,路由切换会卸载当前路由匹配的组件:
<Route path="/home" component={Home} /> // 离开/home路由时Home组件被销毁
手动调用卸载方法
在类组件中,可以通过父组件强制卸载子组件:
class Parent extends React.Component {
state = { showChild: true };
handleUnmount = () => {
this.setState({ showChild: false });
};
render() {
return (
<>
{this.state.showChild && <Child />}
<button onClick={this.handleUnmount}>卸载子组件</button>
</>
);
}
}
组件销毁时的清理工作
组件销毁前会触发生命周期方法,可用于执行清理操作:
类组件清理方式
componentWillUnmount() {
// 清除定时器
clearInterval(this.timer);
// 取消事件监听
window.removeEventListener('resize', this.handleResize);
}
函数组件清理方式
useEffect(() => {
const timer = setInterval(() => {}, 1000);
return () => {
clearInterval(timer);
// 其他清理逻辑
};
}, []);
注意事项
- 避免在已销毁组件中调用
setState,这会引发内存泄漏警告 - 清除所有订阅和异步任务,包括:
- 定时器(setTimeout/setInterval)
- 事件监听器
- WebSocket连接
- AJAX请求取消(使用AbortController)
- 使用严格模式(StrictMode)可以帮助识别未正确清理的副作用







