使用createRoot()方法创建的react组件在调用ReactDOM.unmountComponentAtNode()方法卸载报错的解决方案

本文介绍了如何在使用createRoot()方法创建的React组件上正确执行unmountComponentAtNode(),避免常见警告,并提供了一个实例演示。关键在于确保父组件更新状态并重新渲染来移除组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

报错:

Warning: unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. Instead, have the parent component update its state and rerender in order to remove this component.

Warning: You are calling ReactDOM.unmountComponentAtNode() on a > container that was previously passed to ReactDOMClient.createRoot(). > This is not supported. Did you mean to call root.unmount()?

翻译:

警告:unmountComponentAtNode():您试图卸载的节点由React渲染,不是顶级容器。相反,请父组件更新其状态并重新读取,以便删除此组件。
警告:您正在调用ReactDOM。在之前传递给ReactDOMClient.createRoot()的>容器上卸载ComponentAtNode()。>这不受支持。你是想调用root.unmount()吗?

告诉你使用createRoot()方法创建的react组件不能被ReactDOM.unmountComponentAtNode()方法直接卸载,下面是要进行卸载的组件

1.导出root

const container = document.getElementById('root')
const root = createRoot(container)
export default root

2.执行

//在要执行卸载的组件的方法中执行这个方法
root.unmount()

就可以卸载了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值