main.tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import {BrowserRouter} from 'react-router-dom'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<App/>
</BrowserRouter>
</React.StrictMode>
)
router文件夹
index.tsx
import React,{lazy} from 'react'
import Login=lazy(()=>import('@/views/Login/index'))
import Home from '@/views/Home'
import Page1=lazy(()=>import('@/views/Page1'))
import Page2=lazy(()=>import('@/views/Page2'))
import Page301=lazy(()=>import('@/views/Page301'))
import {Navigate} from 'react-router-dom'
const withLoadingComponent=(comp:JSX.Element)=>{
<React.Suspense fallback={<div>Loading...</div>}>
{comp}
</React.Suspense>
}
const routes=[
{
path:'/',
element:<Navigate to='/page1'>
},
{
path:'/',
element:<Home/>,
children:[
{
path:'/page1',
element:withLoadingComponent(<Page1/>)
},
{
path:'/page2',
element:withLoadingComponent(<Page2/>)
},
{
path:'/page3/page301',
element:widthLoadingComponent(<Page301/>)
}
]
},
{
path:'/login',
element:<Login/>
},
]
export default routes;
顶级组件App.tsx
无路由拦截
import {useRoutes} from 'react-router-dom'
import router from './router'
function App(){
const outlet=useRoutes(router)
return {
<>
{outlet}
</>
}
}
export default App
路由拦截
import {useRoutes,useLocation,useNavigate} from 'react-router-dom'
import {useEffect} from 'react'
import router from './router'
function ToPage1(){
const navigateTo=useNavigate()
useEffect(()=>{
navigateTo('/page1')
},[])
return <div></div>
}
function ToLogin(){
const navigateTo=useNavigate()
useEffect(()=>{
navigateTo('/login')
},[])
return <div></div>
}
function BeforeRouterEnter(){
const outlet=useRoutes(router)
const location=useLocation()
let token=localStorage.getItem('react-ts-token')
if(location.pathname==='/login'&&token){
message.warning('请先退出')
return <ToPage1/>
}else if(location.pathname!=='/login'&&!token){
message.warning('请先登录')
return <ToLogin/>
}
}
function App(){
return (
<>
<BeforeRouterEnter/>
</>
)
}
export default App