react 实现路由拦截

简单介绍下项目背景,我这里做了一个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组件懒加载的时候,路由跳转了,由于网络原因,组件内容无法及时过去,不添加会报错。 

相关推荐

  1. react 实现拦截

    2024-02-19 06:32:02       29 阅读
  2. vue与react拦截

    2024-02-19 06:32:02       35 阅读
  3. react native使用TS实现

    2024-02-19 06:32:02       17 阅读
  4. uni-app中添加拦截

    2024-02-19 06:32:02       7 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-19 06:32:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-19 06:32:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-19 06:32:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-19 06:32:02       20 阅读

热门阅读

  1. 深入理解nginx的动态变量机制【上】

    2024-02-19 06:32:02       24 阅读
  2. golang 获取域名 ip dns 信息

    2024-02-19 06:32:02       27 阅读
  3. Redis分布式可重入锁实现方案

    2024-02-19 06:32:02       26 阅读
  4. 正则表达式的应用

    2024-02-19 06:32:02       24 阅读
  5. AJAX.

    AJAX.

    2024-02-19 06:32:02      35 阅读
  6. 傅雷家书读书札记

    2024-02-19 06:32:02       28 阅读