react實(shí)現(xiàn)路由攔截的示例代碼
簡(jiǎn)單介紹下項(xiàng)目背景,我這里做了一個(gè)demo,前端使用mock數(shù)據(jù),然后實(shí)現(xiàn)簡(jiǎ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組件懶加載的時(shí)候,路由跳轉(zhuǎn)了,由于網(wǎng)絡(luò)原因,組件內(nèi)容無(wú)法及時(shí)過(guò)去,不添加會(huì)報(bào)錯(cuò)。
到此這篇關(guān)于react實(shí)現(xiàn)路由攔截的示例代碼的文章就介紹到這了,更多相關(guān)react路由攔截內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react 原生實(shí)現(xiàn)頭像滾動(dòng)播放的示例
這篇文章主要介紹了react 原生實(shí)現(xiàn)頭像滾動(dòng)播放的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04React中的useState如何改變值不重新渲染的問(wèn)題
這篇文章主要介紹了React中的useState如何改變值不重新渲染的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03Yarn安裝項(xiàng)目依賴(lài)報(bào)error?An?unexpected?error?occurred:?“XXXXX:E
這篇文章主要為大家介紹了Yarn安裝項(xiàng)目依賴(lài)報(bào)error?An?unexpected?error?occurred:?“XXXXX:ESOCKETTIMEOUT”問(wèn)題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03