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


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM