react實(shí)現(xiàn)路由攔截的示例代碼
簡單介紹下項(xiàng)目背景,我這里做了一個demo,前端使用mock數(shù)據(jù),然后實(shí)現(xiàn)簡單的路由攔截,校驗(yàn)session是否包含用戶作為已登錄的依據(jù),react-router-dom是v6。不像vue可以設(shè)置登錄攔截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>
)
}
//實(shí)現(xiàn)路由攔截
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組件懶加載的時候,路由跳轉(zhuǎn)了,由于網(wǎng)絡(luò)原因,組件內(nèi)容無法及時過去,不添加會報(bào)錯。
到此這篇關(guān)于react實(shí)現(xiàn)路由攔截的示例代碼的文章就介紹到這了,更多相關(guān)react路由攔截內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react 原生實(shí)現(xiàn)頭像滾動播放的示例
這篇文章主要介紹了react 原生實(shí)現(xiàn)頭像滾動播放的示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
Yarn安裝項(xiàng)目依賴報(bào)error?An?unexpected?error?occurred:?“XXXXX:E
這篇文章主要為大家介紹了Yarn安裝項(xiàng)目依賴報(bào)error?An?unexpected?error?occurred:?“XXXXX:ESOCKETTIMEOUT”問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03

