Files
vf_react/src/routes/utils/renderRoute.js
2025-10-31 10:33:53 +08:00

74 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 - 懒加载组件或 nullnull 表示使用 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)}
/>
);
}