react如何销毁
销毁 React 组件
在 React 中,销毁组件通常涉及清理副作用(如事件监听器、定时器或订阅)以防止内存泄漏。以下是实现组件销毁的常见方法:
使用 useEffect 清理副作用
在函数组件中,useEffect 的返回函数用于清理操作。当组件卸载时,React 会自动调用该函数。
import React, { useEffect } from 'react';
function ExampleComponent() {
useEffect(() => {
const timer = setInterval(() => {
console.log('Timer running');
}, 1000);
return () => {
clearInterval(timer); // 清理定时器
};
}, []);
return <div>Example Component</div>;
}
类组件中的 componentWillUnmount
在类组件中,通过 componentWillUnmount 生命周期方法实现清理逻辑。

import React from 'react';
class ExampleComponent extends React.Component {
componentDidMount() {
this.timer = setInterval(() => {
console.log('Timer running');
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timer); // 清理定时器
}
render() {
return <div>Example Component</div>;
}
}
手动卸载组件
通过条件渲染或直接操作 DOM 可以触发组件的卸载。
条件渲染
通过状态控制组件的渲染与卸载。

import React, { useState } from 'react';
function ParentComponent() {
const [showChild, setShowChild] = useState(true);
return (
<div>
<button onClick={() => setShowChild(false)}>Unmount Child</button>
{showChild && <ChildComponent />}
</div>
);
}
function ChildComponent() {
useEffect(() => {
return () => {
console.log('Child component unmounted');
};
}, []);
return <div>Child Component</div>;
}
使用 ReactDOM.unmountComponentAtNode
通过 ReactDOM 的 API 直接卸载挂载在 DOM 节点上的组件。
import React from 'react';
import ReactDOM from 'react-dom';
const rootElement = document.getElementById('root');
function unmountComponent() {
ReactDOM.unmountComponentAtNode(rootElement);
}
function App() {
return (
<div>
<button onClick={unmountComponent}>Unmount App</button>
</div>
);
}
ReactDOM.render(<App />, rootElement);
清理事件监听器
在组件卸载时移除事件监听器以避免内存泄漏。
import React, { useEffect } from 'react';
function EventListenerComponent() {
useEffect(() => {
const handleResize = () => {
console.log('Window resized');
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return <div>Resize the window and check console</div>;
}
取消订阅外部数据源
在组件卸载时取消订阅(如 Redux 或 WebSocket)以防止内存泄漏。
import React, { useEffect } from 'react';
import { subscribe, unsubscribe } from 'some-data-source';
function DataSubscriptionComponent() {
useEffect(() => {
subscribe('data-update', (data) => {
console.log('Data updated:', data);
});
return () => {
unsubscribe('data-update');
};
}, []);
return <div>Subscribed to data updates</div>;
}
通过以上方法可以确保组件卸载时资源被正确释放,避免潜在的性能问题。





