分享一个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组件懒加载的时候,路由跳转了,由于网络原因,组件内容无法及时过去,不添加会报错。