react hooks路由守卫实现

react-router-dom V6 hooks 路由守卫实现:

react hooks 函数式组件实现路由守卫与vue实现路由守卫不同,不是依靠router的内置函数,而是通过组件完成。

react中<Outlet />组件类似于vue中的<router-view />,用于匹配子组件,核心思想是新建一个路由守卫组件,用于处理逻辑,是否返回<Outlet />。

组件结构如下:

 代码如下:

import { useNavigate, useLocation } from "react-router-dom";
import { Outlet } from "react-router-dom";
import { useEffect } from "react";
import { message } from "antd";
const RouterBeforeEach = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const noLoginUrl = [ //白名单路由
    "/login",
  ];
  useEffect(() => {
    const isLogin = false;//登录逻辑判断
    if (isLogin) {
      if (noLoginUrl.indexOf(location.pathname) === -1) {
        message.warning("请先登录");
        navigate("/app/home");
        return
      }
    }
  }, [location.pathname]);
  return <Outlet />;
};

export default RouterBeforeEach;

猜你喜欢

转载自blog.csdn.net/weixin_44510655/article/details/128531913