这是最近在重新学习react的过程中遇到的问题,也是我记录下当接触是怎么使用的吧!!保姆级别的。。。 我这里应该使用的是最新的版本了吧react-router-dom: ^6.8.1。不做解释,直接上代码,项目先跑起来再说。
第一步,先看下我的页面结构吧
解释一下:
app.js为入口文件,就不用多说了吧,
一级路由:NotFound、loginPage以及LayoutPage。
二级路由:是user下的页面,作为LayoutPage的子路由。
第二步、封装一下路由懒加载
LazyLoad.js
// 路由懒加载的封装
import { Suspense, lazy } from "react"
const LazyLoad = (path) => {
//相信你能看懂,我也能看懂,这就是封装了下引入路径嘛,后面不用写views了
const Comp = lazy(() => import("../views" + path))
return (
<div>
<Suspense fallback={<>加载中...</>}>
<Comp />
</Suspense>
</div>
)
}
export default LazyLoad
第三步、封装路由
routerConfig.js
import { useRoutes } from "react-router-dom"
import LazyLoad from "../utils/LazyLoad"
import LayoutPage from "../views/layout/index"
// 整个项目的路由表,我这里直接return了个函数
export const Routes = () => {
return useRoutes([
{
path: "/",
//这个layoutPage是属于内容的整体,不能使用懒加载,否则回闪屏
//element: LazyLoad("/LayoutPage"),
//这丫引入就不会出现闪屏的
//import LayoutPage from "../views/layout/index"
element: <LayoutPage />,
//这里就和vue很像了,作为LayoutPage的子路由
children: [
{
//index: true重定向嘛, 相当于访问LayoutPage页面时直接跳转到/user/UserPage页面
index: true,
element: LazyLoad("/user/UserPage"),
}
],
},
{
path: "/*",
element: LazyLoad("/NotFound"),
},
{
path: "/login",
element: LazyLoad("/LoginPage"),
},
])
}
第四步、页面使用
封装好路由,直接在app.js中引入,就能渲染,不知道为啥,还没研究
import { Routes } from "./router/routerConfig"
function App() {
return Routes()
}
export default App
再一个就是你在LayoutPage下写了个子路由,肯定要像vue中的一样啊,在LayoutPage使用一个像router-view一样的标签啊,要不怎么渲染children子路由啊,在react中使用的是Outlet LayoutPage页面
import { Outlet } from "react-router-dom"
function LayoutPage() {
return (
<div className="LayoutPage">
<Outlet />
</div>
)
}
export default LayoutPage
完工、页面显示
重定向到user页面
到登录页面
先写这么多吧,先会用再说其他的