react create-react-app 配置路由报错(Uncaught TypeError: Cannot read properties of null (reading ‘useRef‘))

报错信息:

Uncaught TypeError: Cannot read properties of null (reading ‘useRef’)

The above error occurred in the component:
at BrowserRouter (http://localhost:3000/static/js/bundle.js:4864:5)
at App Consider adding an error boundary to your tree to customize error handling behavior.
报错截图
在这里插入图片描述

解决方案:

我的环境是:

    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router": "^6.16.0",
    "react-router-dom": "^6.16.0",

create-react-app v5

我遇到这个问题时,一开始怀疑语法问题,但最后都排除了。
我的解决方案是:
1.先尝试 清除缓存 执行npm cache clean --force
2.npm start看看行不行
3.如果不行的话,删除node_moudels 然后再cnpm install (我试了几次都可以)
4.最后 npm start就可以了

我觉得原因 可能是node_modules下的.store里造成的,我单独删除 .cache 不行,然后删除.store 直接报错。最后删除整个node_modules才行的。
我的代码如下:
1.首先 npm react-router-dom
2.App.js 里 写上如下代码:

import React from "react";
import {
    
     BrowserRouter, Routes, Route } from "react-router-dom";
import routes from './routes';
const App = () => {
    
    
  console.log(routes)
  return (
    <BrowserRouter>
      <Routes>
        {
    
    routes.map((route) => (
          <Route key={
    
    route.path} path={
    
    route.path} element={
    
    route.component} />
        ))}
        {
    
    /* <Route path="*" element={<Home />} />  */}
      </Routes>
    </BrowserRouter>
  );
};

export default App;

App.js 代码截图
3.index.js里写上:

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

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

// 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();

index.js代码截图

4.在src下新建一个 routes.js文件 写上:

// 导入你的页面组件  
import Home from './pages'; 
const routes = [
  {
    
     path: "/", component: <Home/>}
];

export default routes;

routes.js代码截图
运行看到 Home组件里的东西就说明成功了。之后可以在 scr/router.js里导入其他组件 写上 path和routers就行了。

注意:react-router-dom v6 和v5 api不太一样,比如 v5 把 Route 上是 component v6是element。具体写法 建议参考 你所用的版本 文档!

猜你喜欢

转载自blog.csdn.net/weixin_44058725/article/details/133316898