查看: 15|回复: 0

解决React项目关于升级React 18的报错问题

[复制链接]

3

主题

0

回帖

0

积分

热心网友

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2009-11-21
发表于 2022-4-1 15:45:00 | 显示全部楼层 |阅读模式

当我们使用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

虽然不会影响我们运行项目,但是对于强迫症的我们来说还是不能忍受的。我们在index.js文件中修改下ReactDom就可以消除这个报错:

 

1. 修改前index.js

 

import React from 'react';
import ReactDOM from 'react-dom';  // 未修改前的引入地址
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

// 未修改前的ReactDOM.render()方法
ReactDOM.render(
 <React.StrictMode>
   <App />
 </React.StrictMode>,
 document.getElementById('root')
);

reportWebVitals();

 

2. 修改index.js文件

(1) 修改ReactDom的引入路径为'react-dom/client'

(2) 修改render函数中ReactDom.render() 方法为

  ReactDOM.createRoot(document.getElementById('root')) .render(

    <React.StrictMode>

      <App />

    </React.StrictMode>

  );

修改后index.js

import React from 'react';
import ReactDOM from 'react-dom/client';  // 修改后的引入路径 
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

// 修改后的ReactDom方法
ReactDOM.createRoot(document.getElementById('root')) .render(
  <React.StrictMode>
      <App />
  </React.StrictMode>
);

reportWebVitals();

 



来源:https://www.cnblogs.com/maxiaocang/p/16087320.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部