102 lines
2.7 KiB
JavaScript
102 lines
2.7 KiB
JavaScript
// src/routes/index.js
|
|
// 路由渲染器 - 根据配置自动生成 Routes
|
|
|
|
import React from 'react';
|
|
import { Routes, Route, Navigate } from 'react-router-dom';
|
|
import { Box, useColorMode } from '@chakra-ui/react';
|
|
|
|
// 路由配置
|
|
import { routeConfig, PROTECTION_MODES, getMainLayoutRoutes, getStandaloneRoutes } from './routeConfig';
|
|
|
|
// 布局组件 (非懒加载)
|
|
import Auth from '../layouts/Auth';
|
|
import HomeLayout from '../layouts/Home';
|
|
import MainLayout from '../layouts/MainLayout';
|
|
|
|
// 保护路由组件
|
|
import ProtectedRoute from '../components/ProtectedRoute';
|
|
import ProtectedRouteRedirect from '../components/ProtectedRouteRedirect';
|
|
|
|
/**
|
|
* 根据保护模式包装组件
|
|
*/
|
|
function wrapWithProtection(Component, protection) {
|
|
if (protection === PROTECTION_MODES.MODAL) {
|
|
return (
|
|
<ProtectedRoute>
|
|
<Component />
|
|
</ProtectedRoute>
|
|
);
|
|
}
|
|
|
|
if (protection === PROTECTION_MODES.REDIRECT) {
|
|
return (
|
|
<ProtectedRouteRedirect>
|
|
<Component />
|
|
</ProtectedRouteRedirect>
|
|
);
|
|
}
|
|
|
|
// PUBLIC - 无保护
|
|
return <Component />;
|
|
}
|
|
|
|
/**
|
|
* 渲染单个路由
|
|
*/
|
|
function renderRoute(routeItem, index) {
|
|
const { path, component, protection } = routeItem;
|
|
|
|
// 处理特殊组件(非懒加载)
|
|
let Component;
|
|
if (component === 'Auth') {
|
|
Component = Auth;
|
|
} else if (component === 'HomeLayout') {
|
|
Component = HomeLayout;
|
|
} else {
|
|
Component = component;
|
|
}
|
|
|
|
return (
|
|
<Route
|
|
key={`${path}-${index}`}
|
|
path={path}
|
|
element={wrapWithProtection(Component, protection)}
|
|
/>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* AppRoutes - 应用路由组件
|
|
* 替代 App.js 中的 Routes 部分
|
|
*/
|
|
export function AppRoutes() {
|
|
const { colorMode } = useColorMode();
|
|
|
|
// 分离路由
|
|
const mainLayoutRoutes = getMainLayoutRoutes();
|
|
const standaloneRoutes = getStandaloneRoutes();
|
|
|
|
return (
|
|
<Box minH="100vh" bg={colorMode === 'dark' ? 'gray.800' : 'white'}>
|
|
<Routes>
|
|
{/* 带导航栏的主布局 - 所有需要导航栏的页面都在这里 */}
|
|
<Route element={<MainLayout />}>
|
|
{mainLayoutRoutes.map((route, index) => renderRoute(route, index))}
|
|
</Route>
|
|
|
|
{/* 不使用布局的路由 */}
|
|
{standaloneRoutes.map((route, index) => renderRoute(route, index))}
|
|
|
|
{/* 默认重定向到首页 */}
|
|
<Route path="/" element={<Navigate to="/home" replace />} />
|
|
|
|
{/* 404 页面 */}
|
|
<Route path="*" element={<Navigate to="/home" replace />} />
|
|
</Routes>
|
|
</Box>
|
|
);
|
|
}
|
|
|
|
export default AppRoutes;
|