一、安装路由
npm install react-router-dom@6
结构目录
App.tsx
import React from 'react';
import { BrowserRouter } from 'react-router-dom'
// import logo from './logo.svg';
import './App.css';
import Layout from './layout'
function App() {
return (
<div className="App">
<BrowserRouter>
<React.Suspense fallback={<>正在加载……</>}>
<Layout />
</React.Suspense>
</BrowserRouter>
</div>
);
}
export default App;
router / index.tsx
路由组件遍历渲染
import { Route } from 'react-router-dom'
import { routes, IRoute } from './routes'
export const RouteData = (data: any[]) => {
return data.map((item: IRoute, index: number) => {
return (
<Route
key={item?.key ? item?.key : index}
path={item?.path}
element={item?.element}
caseSensitive={item?.caseSensitive}
>
{/* {item?.children ? RouteData(item?.children) : null} */}
{item?.children && item?.children?.map((child: any) => {
return <Route
key={child?.key ? item?.key : item?.path}
path={child?.path}
element={child?.element}
caseSensitive={item?.caseSensitive}
/>
})}
</Route>
)
})
}
export const routeRender = RouteData(routes)
router / routes.tsx
路由接口与路由数据
import React from 'react'
const Home = React.lazy(() => import('src/pages/home'))
const Childrenpages = React.lazy(() => import('src/pages/childrenpages'))
const Graph = React.lazy(() => import('src/pages/graph'))
export interface IRoute {
caseSensitive?: boolean;
children?: Array<IRoute>
element?: React.ReactNode | null;
index?: false;
path: string;
key?: any;
title?: string;
[name: string]: any;
}
export const routes: Array<IRoute> = [
{
path: '/',
element: <Home />,
children: [
{
path: 'childrenpages',
element: <Childrenpages />
}
]
},
{
path: 'graph',
element: <Graph />,
},
{
path: 'childrenpages321',
element: <Childrenpages />,
}
]
layout / index.tsx
在布局文件中引入路由
import React from 'react';
import { Routes, Outlet } from 'react-router-dom'
import { routeRender } from '../router'
// import { routes } from '../router/routes'
class Layout extends React.Component {
render(): React.ReactNode {
console.log(routeRender);
return (
<div id='layout'>
<Routes>
{/* {RouteData(routes)} */}
{routeRender}
</Routes>
<Outlet />
</div>
)
}
}
export default Layout
使用路由的文件
home / index.tsx
import React from 'react'
import { useNavigate, Outlet } from 'react-router-dom'
const Home: React.FC = (props) => {
const navigate = useNavigate();
const gorouter = () => {
navigate('/graph')
}
return (
<div id='home' onClick={gorouter}>123 <Outlet /></div>
)
}
export default Home
这里出现了路由嵌套,按照react-router-dom
的介绍,需要在父级使用<Outlet />
为子路由占位,才会在跳转子路由时渲染
使用useNavigate
做路由跳转,使用绝对路由进行跳转,相对路由会进行url拼接跳转
后续再详细更新……
参考:
React-Router v6 新版本路由封装
react-router-dom v6 使用
React-Router v6 新特性解读及迁移指南
react-router-dom v6 版本使用内容详解