新建的React项目,启动后控制台警告如下:
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入口文件为:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
// 使用createRoot
import { createRoot } from 'react-dom/client';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);
// ReactDOM.render( // 原来的代码
// <React.StrictMode>
// <App />
// </React.StrictMode>,
// document.getElementById('root')
// );
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
控制台警告消失。
这篇博客介绍了在React 18中,ReactDOM.render已不再支持,改用createRoot作为新的渲染API。作者提供了修改index.js入口文件以消除控制台警告的具体步骤,并提醒开发者,如果不进行更新,应用将按React 17的方式运行。遵循这些更改,可以确保应用兼容React 18并遵循最佳实践。


被折叠的 条评论
为什么被折叠?



