Skip to content

Commit d56dad8

Browse files
committed
optimize: 补充useRoute
1 parent a29807a commit d56dad8

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

src/features/router/useRoute.ts

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,45 @@ import { useMatches, useRouteError } from 'react-router-dom';
22

33
import { parseQuery } from './query';
44

5+
function usePrevious<T>(value: T): T | null {
6+
const ref = useRef<T>(null);
7+
8+
useEffect(() => {
9+
ref.current = value;
10+
}, [value]);
11+
12+
return ref.current;
13+
}
14+
515
/** - get route meta */
616
export function useRoute<T = unknown, Q extends Record<string, string> = Record<string, string>>() {
717
const matches = useMatches();
818

9-
const route = matches.at(-1) as Router.Route<T>;
19+
const routes = matches.at(-1) as Router.Route<T>;
1020

1121
const { hash, pathname, search } = useLocation();
1222

23+
const fullPath = pathname + search + hash;
24+
1325
const query = parseQuery(search) as Q;
1426

15-
const error = useRouteError();
27+
const error = useRouteError() as Error | null;
1628

17-
return {
18-
...route,
29+
const route = {
30+
...routes,
1931
error,
20-
fullPath: pathname + search + hash,
32+
fullPath,
33+
hash,
2134
matched: matches.slice(1) as Router.Route<T>[],
35+
pathname,
2236
query,
37+
redirect: null,
2338
search
24-
};
39+
} as Router.Route<T, Q>;
40+
41+
const previousRoute = usePrevious(route);
42+
43+
route.redirect = previousRoute;
44+
45+
return useMemo(() => route, [route.fullPath]);
2546
}

0 commit comments

Comments
 (0)