插件窝 干货文章 react实现路由拦截的示例代码

react实现路由拦截的示例代码

react element const import 786    来源:    2024-10-18

简单介绍下项目背景,我这里做了一个demo,前端使用mock数据,然后实现简单的路由拦截,校验session是否包含用户作为已登录的依据,react-router-dom是v6。不像vue可以设置登录拦截beforeenter,react需要我们自己加。

//router.js
import React, { lazy } from "react";
import { Navigate } from 'react-router-dom'
 
const Error = lazy(() => import("@/pages/Error/Error.jsx"))
const Index = lazy(() => import("@/pages/Index/Index.jsx"))
const Login = lazy(() => import("@/pages/Login/Login.jsx"))
 
export const routes = [
    {
        path: "/",
        element: <Navigate to="/index"/>
    },
    {
        path: "/login",
        element: <Login />
    },
    {
        path: "/index",
        element: <Index />
    },
    {
        path: "*",
        element: <Error />
    },
]
import React, { useEffect, Suspense } from 'react'
import { useRoutes, useNavigate } from 'react-router-dom'
import { routes } from './router'
 
export default function Index() {
    const element = useRoutes(routes)
 
    return (
        <Authen route={element} children={element.children}>
            <Suspense>
                <div>{element}</div>
            </Suspense>
        </Authen>
    )
 
}
//实现路由拦截
const Authen = (props) => {
    const navigate = useNavigate()
    const { route, children } = props
    const username = sessionStorage.getItem('username')
    console.log(props);
    useEffect(() => {
        if (route.props.match.pathname === "/login" && username) {
            navigate('/index')
        }
    }, [route, navigate,username])
    return children
}
 

Surpense组件是react组件懒加载的时候,路由跳转了,由于网络原因,组件内容无法及时过去,不添加会报错。 

到此这篇关于react实现路由拦截的示例代码的文章就介绍到这了,更多相关react路由拦截内容请搜索插件窝以前的文章或继续浏览下面的相关文章希望大家以后多多支持插件窝!