You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用React Router创建专门用于管理路由的独立组件?

实现步骤

1. 新建Route.js文件,定义路由配置和路由组件

你可以先把所有路由规则抽成统一的配置数组,再封装成可复用的路由组件,后续维护路由只需要修改配置数组即可,代码如下:

// Route.js
import { Switch, Route } from 'react-router-dom'
// 此处按你项目的实际路径引入各个路由对应的页面组件,示例:
// import Home from './pages/Home'
// import MessageList from './pages/messages/MessageList'
// import CeoStats from './pages/messages/CeoStats'
// 其余页面组件按实际情况补充引入即可

// 路由配置表
export const routeConfig = [
  {
    path: '/',
    exact: true,
    component: () => <h1>首页</h1> // 替换为你实际的首页组件
  },
  {
    path: '/messages/messagelist',
    exact: true,
    component: () => <h1>消息列表</h1> // 替换为实际对应的页面组件
  },
  {
    path: '/messages/ceostats',
    exact: true,
    component: () => <h1>CEO数据面板</h1> // 替换为实际对应的页面组件
  },
  {
    path: '/resourcem/categories',
    exact: true,
    component: () => <h1>资源分类</h1> // 替换为实际对应的页面组件
  },
  {
    path: '/resourcem/subcategories',
    exact: true,
    component: () => <h1>资源子分类</h1> // 替换为实际对应的页面组件
  },
  {
    path: '/resourcem/resources',
    exact: true,
    component: () => <h1>资源列表</h1> // 替换为实际对应的页面组件
  },
  {
    path: '/surveys',
    exact: true,
    component: () => <h1>问卷页面</h1> // 替换为实际对应的页面组件
  },
  {
    path: '/userm/users',
    exact: true,
    component: () => <h1>用户列表</h1> // 替换为实际对应的页面组件
  },
  {
    path: '/userm/usergroups',
    exact: true,
    component: () => <h1>用户组列表</h1> // 替换为实际对应的页面组件
  }
]

// 封装路由组件,供给App.js调用
export default function AppRoutes() {
  return (
    <Switch>
      {routeConfig.map((route, index) => (
        <Route
          key={index}
          path={route.path}
          exact={route.exact}
          component={route.component}
        />
      ))}
    </Switch>
  )
}

2. 修改App.js的路由代码

把原来嵌套在Router里的Switch整段替换为刚才封装的AppRoutes组件即可:

// App.js
import { BrowserRouter as Router } from 'react-router-dom'
import AppRoutes from './Route' // 按你项目的实际文件路径调整引入路径

function App() {
  return (
    <Router>
      <AppRoutes />
      {/* 其他全局组件比如导航栏、全局提示、页脚等可以放在此处 */}
    </Router>
  )
}

export default App
优化提示
  • 后续新增、修改路由只需调整Route.js里的routeConfig数组即可,无需修改其他逻辑
  • 可以按需给路由配置项增加name、auth等自定义字段,方便后续扩展权限控制、面包屑生成、菜单渲染等功能

内容的提问来源于stack exchange,提问作者ahmedskulj10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 02:06:01