feat: 添加路由守卫与拦截器
This commit is contained in:
62
src/router/guard.ts
Normal file
62
src/router/guard.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/** @format */
|
||||
|
||||
import { message } from "antd";
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
Location,
|
||||
NavigateFunction,
|
||||
RouteObject,
|
||||
useLocation,
|
||||
useNavigate,
|
||||
useRoutes,
|
||||
} from "react-router-dom";
|
||||
import localforage from "localforage";
|
||||
|
||||
//递归查询对应的路由
|
||||
export function searchRouteDetail(path: string, routes: RouteObject[]): RouteObject | null {
|
||||
for (const item of routes) {
|
||||
if (item.path === path) return item;
|
||||
if (item.children) {
|
||||
return searchRouteDetail(path, item.children);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
//全局路由守卫
|
||||
async function guard(location: Location, navigate: NavigateFunction, routes: RouteObject[]) {
|
||||
const { pathname } = location;
|
||||
|
||||
//找到对应的路由信息
|
||||
const routedetail: RouteObject | null = searchRouteDetail(pathname, routes);
|
||||
|
||||
//没有找到路由,跳转404
|
||||
if (!routedetail) {
|
||||
navigate("/404");
|
||||
return false;
|
||||
}
|
||||
//如果需要权限验证
|
||||
if (
|
||||
routedetail.path !== "/login" &&
|
||||
routedetail.path !== "/register" &&
|
||||
routedetail.path !== "/" &&
|
||||
routedetail.path !== "/404"
|
||||
) {
|
||||
const token: string | null = await localforage.getItem("token");
|
||||
if (!token) {
|
||||
message.warning("请先登录!").then();
|
||||
navigate("/login");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export const RouterGuard = (routes: RouteObject[]) => {
|
||||
const location: Location<any> = useLocation();
|
||||
const navigate: NavigateFunction = useNavigate();
|
||||
useEffect(() => {
|
||||
guard(location, navigate, routes).then();
|
||||
}, [location, navigate, routes]);
|
||||
return useRoutes(routes);
|
||||
};
|
@@ -15,14 +15,14 @@ const routes: RouteObject[] = [
|
||||
path: "/",
|
||||
Component: (props) => ComponentLoading(home, props),
|
||||
},
|
||||
{
|
||||
path: "*",
|
||||
Component: NoFound,
|
||||
},
|
||||
{
|
||||
path: "/register",
|
||||
Component: (props) => ComponentLoading(Register, props),
|
||||
},
|
||||
{
|
||||
path: "/404",
|
||||
Component: (props) => ComponentLoading(NoFound, props),
|
||||
},
|
||||
{
|
||||
path: "/login",
|
||||
Component: (props) => ComponentLoading(Login, props),
|
Reference in New Issue
Block a user