导航

react路由6登录拦截

Posted on 2023-08-01 10:33  晚安圆圆  阅读(277)  评论(0)    收藏  举报

自定义登录拦截组件:

// 路由守卫
// 判断token是否存在,如果存在跳转页面,不存在返回登录页面
import { Navigate } from 'react-router-dom'
 
const getToken = () => {
    return sessionStorage.getItem("token")
}
 
function AuthRouter({children}){
    // 获取token
    const token = getToken()
    // 判断token是否存在
    if(token){
        console.log(children);
        return <>{children}</>
    }else{
        return <Navigate to={'/login'}></Navigate>
    }
}
 
export { AuthRouter }

路由文件夹下引入自定义拦截组件:

包裹需要做拦截的组件就可以实现登录拦截:

import { Navigate, createBrowserRouter as createRouter } from "react-router-dom";
import App from '../App'
import Index from '../pages/Index'
import Tuo from '../pages/Body(1)'
import Login from '../pages/Login'
//做登录拦截
import { AuthRouter } from "./AuthRouter";
const router=createRouter([
    {
        path:'/',
        element:<Navigate to="/login"/>
    },
    {
        path:'/app',
        element:<AuthRouter><App/></AuthRouter>,
        children:[
            {
                path:'index',
                element:<Index/>
            },
            {
                path:'tuo',
                element:<Tuo/>
            }
        ]
    },
    {
        path:'/login',
        element:<Login/>
    }
])
export default router