web-backset.cn/apps/web/src/router/Guard.tsx
2023-03-17 17:58:37 +08:00

29 lines
812 B
TypeScript

import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import Cookies from "js-cookie";
import { useUserStore } from "../store/user.store";
import Result from "../components/Result";
interface IGuardProps {
children: JSX.Element;
}
const needAuthList = ["course/detail"];
export const Guard = (props: IGuardProps) => {
const navigate = useNavigate();
const user = useUserStore((s: any) => s.user);
const fetchUser = useUserStore((s: any) => s.fetchUser);
const location = useLocation();
const sign = Cookies.get("_sign_web");
const needAuth = needAuthList.some((p) => location.pathname.indexOf(p) > -1);
useEffect(() => {
if (!user) fetchUser();
}, [location.pathname]);
if (!sign && needAuth) return <Result />;
return props.children;
};