React18报错警告:You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. 解决办法
React18报错警告
react_devtools_backend_compact.js:2367 Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it ,为什么,解决办法是什么?
这个警告是因为在相同的容器上多次调用createRoot()
方法。这通常发生在React应用程序中在多个地方使用createRoot()
创建多个根渲染器时。在这种情况下,当我们尝试在同一个容器上调用createRoot()
方法时,React会发出上述警告。
解决办法
解决办法是,在第一次调用createRoot()
方法创建根渲染器后,在其他位置不要再次使用createRoot()
方法。而是应该使用已经存在的根渲染器来更新它,可以使用root.render()
方法更新已经存在的根渲染器。
- 如果你确实需要再次创建根渲染器,则应该使用不同的容器来避免这个问题。
- 如果不需要多个根渲染器,需要判断是否已经通过
createRoot()
方法创建了根渲染器,通过判断ReactDOMRoot这个对象中是否存在**_internalRoo**
当你想在一个容器上多次调用createRoot()
方法时,就会出现这个警告。以下是一个例子:
import {createRoot} from 'react-dom/client;
const container = document.getElementById('app');
// 第一次调用 createRoot()
const root1 = createRoot(container);
root1.render(<App />);
// 第二次调用 createRoot(),会导致警告
const root2 = createRoot(container);
root2.render(<AnotherComponent />);
在这个例子中,我们在同一个容器上创建了两个根渲染器(root):root1和root2。第二次调用createRoot()
方法时,React就会发出上述警告。
为了避免这个问题,我们应该避免在相同的容器上多次调用createRoot()
方法。如果我们确实需要创建多个根渲染器,应该使用不同的容器或在不同的组件中进行渲染。以下是一个解决方法:
import {createRoot} from 'react-dom/client;
const container1 = document.getElementById('app1');
const container2 = document.getElementById('app2');
// 在不同的容器上创建根渲染器
const root1 = createRoot(container1);
root1.render(<App1 />);
const root2 = createRoot(container2);
root2.render(<App2 />);
在这个例子中,我们在两个不同的容器上创建了两个根渲染器(root):root1和root2),避免了在同一个容器上多次调用createRoot()
方法,从而避免了上述警告。
let root = null
export default function confirm(config: ModalFuncProps) {
let div = document.getElementById('confirm-container');
if (!div) {
div = document.createElement('div');
div.id = 'confirm-container';
document.body.appendChild(div);
}
if (!root?._internalRoot) root = createRoot(div)
root.render(<app/>)
}