74 lines
2.4 KiB
JavaScript
74 lines
2.4 KiB
JavaScript
// src/routes/utils/renderRoute.js
|
||
// 路由渲染工具函数
|
||
|
||
import React from 'react';
|
||
import { Route, Outlet } from 'react-router-dom';
|
||
import { wrapWithProtection } from './wrapWithProtection';
|
||
|
||
/**
|
||
* 渲染单个路由
|
||
*
|
||
* 根据路由配置项生成 React Router 的 Route 组件。
|
||
* 处理以下逻辑:
|
||
* 1. 解析组件(懒加载组件 or Outlet)
|
||
* 2. 应用路由保护(根据 protection 字段)
|
||
* 3. 处理嵌套路由(children 数组)
|
||
* 4. 生成唯一 key
|
||
*
|
||
* @param {Object} routeItem - 路由配置项(来自 routeConfig.js)
|
||
* @param {string} routeItem.path - 路由路径
|
||
* @param {React.ComponentType|null} routeItem.component - 懒加载组件或 null(null 表示使用 Outlet)
|
||
* @param {string} routeItem.protection - 保护模式 (modal/redirect/public)
|
||
* @param {Array} [routeItem.children] - 子路由配置数组(可选)
|
||
* @param {number} index - 路由索引,用于生成唯一 key
|
||
*
|
||
* @returns {React.ReactElement} Route 组件
|
||
*
|
||
* @example
|
||
* // 使用示例
|
||
* const routes = [
|
||
* { path: 'community', component: CommunityComponent, protection: 'modal' },
|
||
* { path: 'home', component: null, protection: 'public', children: [...] },
|
||
* ];
|
||
*
|
||
* routes.map((route, index) => renderRoute(route, index));
|
||
*/
|
||
export function renderRoute(routeItem, index) {
|
||
const { path, component, protection, children } = routeItem;
|
||
|
||
// 解析组件:
|
||
// - 如果是 null,使用 <Outlet /> 用于嵌套路由
|
||
// - 否则直接使用(懒加载组件)
|
||
let Component;
|
||
let isOutletRoute = false;
|
||
|
||
if (component === null) {
|
||
Component = Outlet; // 用于嵌套路由
|
||
isOutletRoute = true;
|
||
} else {
|
||
Component = component; // 直接使用懒加载组件
|
||
}
|
||
|
||
// 如果有子路由,递归渲染
|
||
if (children && children.length > 0) {
|
||
return (
|
||
<Route
|
||
key={`${path}-${index}`}
|
||
path={path}
|
||
element={isOutletRoute ? <Outlet /> : wrapWithProtection(Component, protection)}
|
||
>
|
||
{children.map((childRoute, childIndex) => renderRoute(childRoute, childIndex))}
|
||
</Route>
|
||
);
|
||
}
|
||
|
||
// 没有子路由,渲染单个路由
|
||
return (
|
||
<Route
|
||
key={`${path}-${index}`}
|
||
path={path}
|
||
element={wrapWithProtection(Component, protection)}
|
||
/>
|
||
);
|
||
}
|