ReactDOM.render is no longer supported in React 18.

4,393 阅读1分钟

Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17.

  • 标题完整内容: Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17.

  • 标题的意思是:ReactDOM。React 18不再支持渲染。使用createRoot代替。在你切换到新的API之前,你的应用会表现得像在运行React 17一样。

  • 当你第一次安装 React 18 时,你会在控制台中看到这个警告;

createRoot()

  • createRoot() 是React 18 引入了一个新的根 API;
  • 这个新的根 API 启用了新的并发渲染器,它允许使用并发功能;

解决方案:

  • r18之前根API渲染方式
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(
    <App />,
  document.getElementById("root")
);
  • r18使用这个新的根Api渲染
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

// 为提供的创建一个 React 根container并返回根。
const root = createRoot(document.getElementById("root"));
// 根可用于将 React 元素渲染到 DOM 中
root.render(<App />);
  • 再次打开控制台,就能看到这个警告消失了。