feat: route/index 重构

This commit is contained in:
zdl
2025-10-30 16:58:29 +08:00
parent e6315bf925
commit 2ac27db207
7 changed files with 206 additions and 0 deletions

View File

@@ -0,0 +1,50 @@
// src/routes/utils/renderRoute.js
// 路由渲染工具函数
import React from 'react';
import { Route } from 'react-router-dom';
import { LAYOUT_COMPONENTS } from '../constants';
import { wrapWithProtection } from './wrapWithProtection';
/**
* 渲染单个路由
*
* 根据路由配置项生成 React Router 的 Route 组件。
* 处理以下逻辑:
* 1. 解析组件(特殊布局组件 vs 懒加载组件)
* 2. 应用路由保护(根据 protection 字段)
* 3. 生成唯一 key
*
* @param {Object} routeItem - 路由配置项(来自 routeConfig.js
* @param {string} routeItem.path - 路由路径
* @param {React.ComponentType|string} routeItem.component - 组件或组件标识符
* @param {string} routeItem.protection - 保护模式 (modal/redirect/public)
* @param {number} index - 路由索引,用于生成唯一 key
*
* @returns {React.ReactElement} Route 组件
*
* @example
* // 使用示例
* const routes = [
* { path: 'community', component: CommunityComponent, protection: 'modal' },
* { path: 'auth/*', component: 'Auth', protection: 'public' },
* ];
*
* routes.map((route, index) => renderRoute(route, index));
*/
export function renderRoute(routeItem, index) {
const { path, component, protection } = routeItem;
// 解析组件:
// - 如果是字符串(如 'Auth', 'HomeLayout'),从 LAYOUT_COMPONENTS 映射表查找
// - 否则直接使用(懒加载组件)
const Component = LAYOUT_COMPONENTS[component] || component;
return (
<Route
key={`${path}-${index}`}
path={path}
element={wrapWithProtection(Component, protection)}
/>
);
}

View File

@@ -0,0 +1,44 @@
// src/routes/utils/wrapWithProtection.js
// 路由保护包装工具函数
import React from 'react';
import { PROTECTION_WRAPPER_MAP } from '../constants';
/**
* 根据保护模式包装组件
*
* 根据路由配置的保护模式,使用对应的保护组件包装目标组件。
* 如果没有对应的保护组件(如 PUBLIC 模式),则直接返回原组件。
*
* @param {React.ComponentType} Component - 要包装的组件
* @param {string} protection - 保护模式
* - 'modal': 使用 ProtectedRoute (弹窗登录)
* - 'redirect': 使用 ProtectedRouteRedirect (跳转登录)
* - 'public': 无保护,直接渲染
*
* @returns {React.ReactElement} 包装后的组件元素
*
* @example
* // PUBLIC 模式 - 无保护
* wrapWithProtection(HomePage, 'public')
* // 返回: <HomePage />
*
* @example
* // MODAL 模式 - 弹窗登录
* wrapWithProtection(Community, 'modal')
* // 返回: <ProtectedRoute><Community /></ProtectedRoute>
*/
export function wrapWithProtection(Component, protection) {
const WrapperComponent = PROTECTION_WRAPPER_MAP[protection];
// 如果没有对应的保护组件PUBLIC 模式),直接返回
if (!WrapperComponent) {
return <Component />;
}
return (
<WrapperComponent>
<Component />
</WrapperComponent>
);
}