import { lazy } from "react";
import { Navigate } from "react-router-dom";
// React 组件懒加载
// 封装生成组件的函数
const lazyLoad = (moduleName: string) => {
const Module = lazy(() => import(`views/${moduleName}`));
return <Module />;
};
// 路由鉴权组件(核心代码 )
// children-是props中的属性解构出来的 是组件内部包裹的内容 类似于(Vue中插槽中的内容)
const Appraisal = ({ children }: any) => {
const token = localStorage.getItem("token");
return token ? children : <Navigate to="/login" />;
};
interface Router {
name?: string;
path: string;
children?: Array<Router>;
element: any;
}
const routes: Array<Router> = [
{
path: "/login",
element: lazyLoad("login"),
},
{
path: "/",
element: <Appraisal>{lazyLoad("sand-box")}</Appraisal>,
children: [
{
path: "",
element: <Navigate to="home" />,
},
{
path: "*",
element: lazyLoad("sand-box/nopermission"),
},
],
},
{
path: "*",
element: lazyLoad("not-found"),
},
];
export default routes;
React-router-dom V6路由守卫实现
最新推荐文章于 2024-12-02 10:11:52 发布