monorepo-microservice-rbac/apps/aorta/src/router/index.tsx
2023-09-12 16:19:42 +08:00

43 lines
1.2 KiB
TypeScript

import { baseRoutes, commonRoutes } from "./router.config";
import { Route, RouteObject, Routes, useLocation } from "react-router-dom";
import { RouteGuard } from "./AuthGuard";
import { pathToRegexp } from "path-to-regexp";
import { defaultTitle } from "@/constant";
// export const RouterElements = () => useRoutes(routesConfig);
export type ExpandRouteProps = {
title?: string;
};
export const RouterElements = () => {
const location = useLocation();
/**
* document.title
*/
const currentRoute = [...baseRoutes, ...commonRoutes].find((r) =>
pathToRegexp(location.pathname).test(r.path!)
);
document.title = currentRoute?.title ?? defaultTitle;
/**
* 递归children
*/
const generateRoutes = (routes: (RouteObject & ExpandRouteProps)[]) =>
routes.map((r) => (
<Route key={r.path} path={r.path} element={r.element}>
{r.children && generateRoutes(r.children)}
</Route>
));
return (
<RouteGuard ignorePaths={baseRoutes.map((r) => r.path!)}>
<Routes>
{generateRoutes([...baseRoutes, ...commonRoutes])}
<Route key="notfound" path="*" element={<span>404</span>} />
</Routes>
</RouteGuard>
);
};