
在 react router 6 中,`
React Router 6 不再支持为单个
✅ 正确写法:使用无 path 的 Layout 路由包裹多个子路径
核心思路是:将
{/* 认证相关路由 —— 独立使用 布局 */} }> {renderRoutes(["auth", "register"])} {/* 统一受保护的主布局 —— 所有需 Layout 的路径都嵌套在此之下 */} }> {renderRoutes(["accounts", "accountCreate", "accountEdit"])} {renderRoutes(["accountTypes", "accountTypeCreate", "accountTypeEdit"])} {renderRoutes(["websites", "websiteCreate", "websiteEdit"])}
? 注意: 必须在其 children 中渲染 ,否则嵌套的子路由内容将无法显示:// Layout.tsx import { Outlet } from 'react-router-dom'; export const Layout = () => ( {/* ← 关键!子路由内容将在此处渲染 */} );
? 进阶优化:复用路由渲染逻辑
为避免重复书写 renderRoutes([...]),可进一步封装工具函数,增强可读性与可维护性:
// utils/routing.ts
export const renderRoutes = (keys: string[]) =>
keys.map(key => (
));你甚至可以将路径与对应路由键映射为配置对象,实现完全声明式管理:
const layoutRoutes = [
{ path: "/accounts", keys: ["accounts", "accountCreate", "accountEdit"] },
{ path: "/account-types", keys: ["accountTypes", "accountTypeCreate", "accountTypeEdit"] },
{ path: "/websites", keys: ["websites", "websiteCreate", "websiteEdit"] },
];
// 在 JSX 中使用
}>
{layoutRoutes.map(({ path, keys }) => (
{renderRoutes(keys)}
))}
⚠️ 常见误区与注意事项
- ❌ 错误:
} /> → path 必须为字符串; - ❌ 错误:未在
中使用 → 子路由内容不会渲染; - ✅ 推荐:将认证路由(/auth, /register)与受保护路由严格分离,便于后续添加权限守卫(如 element={
}); - ✅ 提示:所有 renderRoutes(...) 调用中,确保 routes.getRoute(key) 返回符合 RouteProps 类型的对象(含 index、element、path 等字段)。
通过以上结构,你不仅消除了冗余的










