react如何卸载组件
卸载 React 组件的方法
在 React 中卸载组件通常通过条件渲染或手动清理实现,以下是具体方法:
条件渲染卸载 通过状态控制组件的渲染条件,当条件不满足时组件会被自动卸载:

function ParentComponent() {
const [showChild, setShowChild] = useState(true);
return (
<div>
{showChild && <ChildComponent />}
<button onClick={() => setShowChild(false)}>卸载子组件</button>
</div>
);
}
类组件生命周期方法
对于类组件,可以在 componentWillUnmount 中进行清理:
class ChildComponent extends React.Component {
componentWillUnmount() {
// 清理定时器、取消订阅等
clearInterval(this.timer);
}
render() {
return <div>子组件内容</div>;
}
}
函数组件副作用清理
函数组件使用 useEffect 返回清理函数:

function ChildComponent() {
useEffect(() => {
const timer = setInterval(() => {}, 1000);
return () => clearInterval(timer); // 清理函数
}, []);
return <div>子组件内容</div>;
}
使用 Portal 的组件卸载 通过 Portal 渲染的组件需要确保目标 DOM 节点存在:
function Modal({ onClose }) {
return ReactDOM.createPortal(
<div className="modal">
<button onClick={onClose}>关闭</button>
</div>,
document.getElementById('modal-root')
);
}
强制卸载 DOM 节点 非 React 方式(不推荐):
const element = document.getElementById('component');
ReactDOM.unmountComponentAtNode(element);






