File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -2,8 +2,11 @@ import { RouterProvider as Provider } from 'react-router';
2
2
3
3
import { router } from './router' ;
4
4
import { RouterContext } from './router-context' ;
5
+ import { useCacheRoutes } from './routerHooks' ;
5
6
6
7
export const RouterProvider = ( ) => {
8
+ useCacheRoutes ( ) ;
9
+
7
10
return (
8
11
< RouterContext . Provider value = { router } >
9
12
< Provider router = { router . reactRouter } />
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments