发布于 2年前

React 18 createRoot方法:ReactDOM.render is no longer supported in React 18

自React 18开始,ReactDOM.render被废弃,使用React 18会以兼容模式运行旧代码,并且会有类似以下的警告:

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. Learn more: https://reactjs.org/link/switch-to-createroot

使用createRoot

原来渲染方式:

import { render } from 'react-dom';
const container = document.getElementById('app');
render(<App tab="home" />, container);

使用createRoot后:

import { createRoot } from 'react-dom/client';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App tab="home" />);

首先通过createRoot创建root对象,createRoot的参数是应用挂载的Element元素。接着调用root对象的render方法渲染。

index.js的变化

原来方式:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

使用createRoot后:

import React from 'react';

import './index.css';
import App from './App';
import { createRoot } from 'react-dom/client';

const container = document.getElementById('root');
const root = createRoot(container);
root.render(<React.StrictMode>
  <App />
</React.StrictMode>);
©2020 edoou.com   京ICP备16001874号-3