反应-18 | 您正在对之前已传递给 createRoot() 的容器调用 ReactDOMClient.createRoot()

Rah*_*arg 22 reactjs react-18

在我的基于 React 的库中,我在 3 个不同的级别上使用ReactDOM.render。第一级位于根级,我很清楚并使用以下代码替换了它:

import { createRoot } from 'react-dom/client';
    
const root = createRoot(domElement);
root.render(reactElement);
Run Code Online (Sandbox Code Playgroud)

对于其他两个级别(根的子级),我想在指定的 DOM 元素中渲染某个组件。如果我正在使用:

import { createRoot } from 'react-dom/client';

const root = createRoot(childDomElement);
root.render(reactElement);
Run Code Online (Sandbox Code Playgroud)

我收到以下警告:

您正在对之前已传递给 createRoot() 的容器调用 ReactDOMClient.createRoot() 。相反,如果您想更新它,请在现有根上调用 root.render() 。

在特定 DOM 元素中渲染组件的正确方法是什么?

小智 28

这也发生在我身上。对我来说,这是因为DOMContentLoaded回调触发了两次。

我的修复只是确保容器仅渲染一次。

let container = null;

document.addEventListener('DOMContentLoaded', function(event) {
  if (!container) {
    container = document.getElementById('root1') as HTMLElement;
    const root = createRoot(container)
    root.render(
      <React.StrictMode>
        <h1>ZOO</h1>
      </React.StrictMode>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)


Vit*_* EL 5

您可能从入口点文件导入某些内容,导致入口点文件以某种方式运行两次。我遇到了同样的问题,并通过确保没有从入口点文件导入任何内容来解决它。


Rah*_*arg -3

答案就在警告本身中。

您正在对之前已传递给 createRoot() 的容器调用 ReactDOMClient.createRoot() 。

我最后出现警告的根本原因是同一个 DOM 元素多次用于创建根。

为了解决这个问题,需要确保在一个 DOM 元素createRoot上只调用一次,之后就可以用于更新,而不应该再使用。root.render(reactElement);createRoot