路由全局管理
在src/router/ routes.tsx文件内填写路由配置:
import Oaindex from '@/pages/Oaindex'
import Login from '@/pages/Login'
// 定义路由中的元素类型
interface Router {
path: string;
name?: string;
children?: Array<Router>;
element: any;
}
// 全局路由配置
const routes: Array<Router> = [
{
path: '/oaindex',
name: 'oaindex',
element: <Oaindex />
},
{
path: '/login',
name: 'login',
element: <Login />,
},
]
export default routes;
在项目入口文件src/index.tsx
里引入router组件:
- 路由 browser / history 模式使用
BrowserRouter
,hash 模式使用HashRouter
。
import React from 'react';
import ReactDOM from 'react-dom/client';
import './css/index.css';
import App from './App';
import { BrowserRouter } from 'react-router-dom'
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
项目入口组件src/App.tsx
里引入routes配置:
import React from 'react';
import './css/App.css';
import { useRoutes } from 'react-router-dom'
import routes from '@/router/routes'
function App() {
const elements = useRoutes(routes)
return <div className="App">{elements}</div>;
}
export default App;
全局路由拦截
在src/router/ routes.tsx文件内添加路由拦截,并重新转化路由:
import { Navigate, useRoutes } from 'react-router-dom'
import routes from './routes'
// 路由拦截
const RouterBeforeEach = (props: { route: any, children: any }) => {
if (props?.route?.meta?.title) {
document.title = props.route.meta.title;
}
// 判断是否已登录
const isLogin = localStorage.getItem('Authorization');
// 未登录 需要身份验证的跳转到登录页面
if (!isLogin && props?.route?.meta?.requiresAuth) {
return <Navigate to={'/login'} replace />
}
// 已登录 登录页面需要跳转到默认页面
if (isLogin && ['/login'].includes(props?.route?.path)) {
return <Navigate to={'/'} replace />
}
return props.children
}
// 转化路由
const resolveRoute = (routes: any) => {
return routes.map((item: any) => {
const route = { path: item.path, element: item.element, children: item.children };
// 递归处理子路由
if (item.children) {
route.children = resolveRoute(item.children)
}
if (item.redirect) {
// 重定向
route.element = <Navigate to={item.redirect} />
} else if (route.element) {
route.element = <RouterBeforeEach route={item}>{item.element}</RouterBeforeEach>
} else if (item.component) {
// element 要接收react.element类型 item.component 是对象 所以要转一下
route.element = <RouterBeforeEach route={item}>{item.component} </RouterBeforeEach>
}
return route
})
}
export default function Router() {
return useRoutes(resolveRoute(routes))
}
更改项目入口组件src/App.tsx中路由引入
import React from 'react';
import './css/App.css';
import Router from '@/router'
function App() {
return <div className="App"><Router /></div>;
}
export default App;