React 中如何正确的将多个路由打包给外部调用?

作者站长头像
站长
· 阅读数 12

我在用 react 写一个网页项目,其结构大概如下

my-react-app/
|-- src/
|   |-- components/
|   |-- pages/
|   |   |-- MainPage.jsx
|   |   |-- Auth/
|   |   |   |-- Login.jsx
|   |-- routes/
|   |   |-- authRoutes.jsx
|   |   |-- index.jsx
|   |-- App.jsx
|   |-- index.js
|-- public/
|   |-- index.html
|-- package.json

路由用的是 react-router-dom v6.0+。在路由文件夹 routes 中,其中 authRoutes.jsx 这个文件是用来管理注册登录等路由的,代码如下

import React from 'react';
import { Route } from 'react-router-dom';
import Login from '../pages/Auth/Login';

const AuthRoutes = () => {
  return (
    <>
      <Route path="/auth/login" element={<Login />} />
    </>
  );
}

export default AuthRoutes;

而 routes/index.jsx 这个文件是用来把所有的路由都打包出去的,其代码如下

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import MainPage from '../pages/MainPage';
import AuthRoutes from './authRoutes';

const AllRoutes = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<MainPage />} />
        <AuthRoutes />
      </Routes>
    </Router>
  );
}

export default AllRoutes;

在 app.jsx 中引入如下

import React from 'react';
import AllRoutes from './routes';

import './App.scss'

function App() {
  return (
    <div className="App">
      <AllRoutes />      
    </div>
  );
}

export default App;

我现在遇到的问题是总是提示错误,错误信息是

[AuthRoutes] is not a component. All component children of must be a or <React.Fragment>

我做了一些尝试

  1. 将 authRoutes.jsx 文件中的 <></> 改成了 <React.Fragment></React.Fragment>,还是同样的错误。
  2. 同样,将它们改成 <Routes>,也是同样的错误。
  3. <Route path="/auth/login" element={<Login />} /> 改成了 <Route path="/auth/login" element={ Login } />,还是同样的错误。
  4. 将 routes/index.jsx 中的 <AuthRoutes /> 改成 <Route path="/" element={<AuthRoutes />} />,错误没了,但访问 /auth/login,提示 /auth/login 路径并不存在。
回复
1个回答
avatar
test
2024-06-23

<AuthRoutes /> 改成 {AuthRoutes()} 就行了

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容