Skip to content

Commit 10b2988

Browse files
committed
feat: 添加初始化缓存路由的相关代码
1 parent 5ed2bed commit 10b2988

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/features/router/RouterProvider.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@ import { RouterProvider as Provider } from 'react-router';
22

33
import { router } from './router';
44
import { RouterContext } from './router-context';
5+
import { useCacheRoutes } from './routerHooks';
56

67
export const RouterProvider = () => {
8+
useCacheRoutes();
9+
710
return (
811
<RouterContext.Provider value={router}>
912
<Provider router={router.reactRouter} />

src/features/router/routerHooks.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import type { RouteObject } from 'react-router';
2+
3+
import { routes as allRoutes } from '@/router';
4+
import { setCacheRoutes } from '@/store/slice/route';
5+
6+
function filterCacheRoutes(routes: RouteObject[]) {
7+
const cacheRoutes: string[] = [];
8+
9+
for (const route of routes) {
10+
const { children, handle, path } = route;
11+
// 如果节点存在 path(注意:这里假设空字符串或 undefined 均视为无 path)
12+
if (path) {
13+
if (handle?.keepAlive) {
14+
cacheRoutes.push(path);
15+
}
16+
17+
if (children && children.length) {
18+
cacheRoutes.push(...filterCacheRoutes(children));
19+
}
20+
} else if (children && children.length) {
21+
// 如果当前节点没有 path,但有 children,则递归处理 children,
22+
cacheRoutes.push(...filterCacheRoutes(children));
23+
// 如果既没有 path 也没有 children,则该节点直接被过滤掉
24+
}
25+
}
26+
27+
return cacheRoutes;
28+
}
29+
30+
export function useCacheRoutes() {
31+
const dispatch = useAppDispatch();
32+
33+
const cacheRoutes = filterCacheRoutes(allRoutes);
34+
35+
console.log(cacheRoutes, 'cacheRoutes');
36+
37+
useEffect(() => {
38+
dispatch(setCacheRoutes(cacheRoutes));
39+
}, [cacheRoutes]);
40+
}

0 commit comments

Comments
 (0)