方式一:
1.rsf生成函数组件
2.根组件外边包裹一个路由管理组件 (并包裹app)
import { BrowserRouter,HashRouter } from 'react-router-dom';
<BrowserRouter>
<App />
</BrowserRouter>
3.在app.js中导入路由组件 例如:
import { Route } from 'react-router-dom';
懒加载导入:var Index = lazy(()=>import('@/views/Index'))
4.需要引入Routes组件包裹Route
1.路由六:Routes 路由五:Switch
2.路由重定向:六:Navigate; 五::Redirect
5.二级配置如下:
<Routes>
<Route path='/index' element={<Index />} >
<Route path='/index/home' element={<Home />} />
<Route path='/index' element={<Navigate to='/index/home'/>} />
<Route path='*' element={<NotFound />} />
</Route>
<Route path='/login' element={<Login />} />
<Route path='/' element={<Navigate to='/index'/>} />
<Route path='*' element={<NotFound />} />
</Routes>
6.在index.jsx中使用: (占位组件)
{/* 路由规则——占位组件 */}
<Outlet />
方式二:
在router文件夹下面创建一个routes.js文件并配置在导出
import {Navigate} from 'react-router-dom' //导入重定向
import React, { lazy } from 'react'; //懒加载
// 一级引入
var Index = lazy(() => import('@/views/Index'))
// 二级引入
var Home = lazy(() => import('@/views/Index/Home'))
//配置路由表:
export default [
{
path:'/index',
element:<Index />,
children:[
{
path:'/index/home',
element:<Home />,
},
{
path:'/index/cation',
element:<Cation />,
},
},
{
path:'/',
element:<Navigate to='/index' />, // 重定向
},
{
path:'*',
element:<NotFound />, // 重定向
}
]
2.在app文件中导入配置路由表:
import React, { lazy, Suspense } from 'react'; //suspense是loading动画加载
import { useRoutes } from 'react-router-dom'; //调用路由函数
import routes from './router/routes'; //导入刚才的配置的路由表并调用
<Suspense fallback={<div className='loading'><img src="https://hbimg.b0.upaiyun.com/5ac0d375bfb83e892b4884bb1d7e5046d223da2d2bd08-LrjhBO_fw658" alt="" /></div>}>
{/* // 负责动态生成整个应用程序的路由配置表 */}
{
useRoutes(routes)
}
<Tabbar/>
</Suspense>