新版本React卸载组件遇到问题-----Uncaught Error: unmountComponentAtNode(...): Target container is not a DOM element.
//这是新版index.js的容器命名与挂载方式
import React from 'react'; import {createRoot} from 'react-dom/client'; import { BrowserRouter } from 'react-router-dom'; import App from './App'; const container = document.getElementById('container'); const root = createRoot(container); root.render(<BrowserRouter><App/></BrowserRouter>)
//root暴露出去 export default root;
这是卸载方式:
将老版本的:
<button onClick={this.unmount}>卸载</button>
unmount = ()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('container'))
}
改为:
//在这里要引入root,其位置就在上面index.js的路径中
<button onClick={this.unmount}>卸载</button>
unmount = ()=>{
root.unmount(document.getElementById('container'));
}