一、安装
yarn add react-router-dom@6
npm install react-router-dom@6
二、v6新版本属性改变
-
重命名为。
- 的新特性变更。
- 嵌套路由变得更简单。
- 用useNavigate代替useHistory。
- 新钩子useRoutes代替react-router-config。
- 大小减少:从20kb到8kb
三、准备loading组件
四、封装解析
1.使用BrowserRouter,当然也可以使用HashRouter。BrowserRouter as Router重命名是为了一旦需要换成HashRouter,可以直接在此替换,不要修改下方代码。 2.通过index.js的路由配置遍历路由,以及路由拦截,判断是否已登录或者404
if (!noAuth && !token) return <Route path="*" element={<Navigate to="/login" />} />;
3.404页面可以使用自己封装的,也可使用包自带的,代码如下
< Route path="*" element={<NotFind to="/login" />} />
4.代码
import * as React from "react";
import { Routes, Route, BrowserRouter as Router, Navigate } from "react-router-dom";
import Loading from "components/loading";
import NotFind from "components/notFind";
import { mainRouteConfig } from "./config";
const renderRouter = (routerList) => {
return routerList.map((item) => {
const { path, exact, noAuth, children } = item;
const token = localStorage.getItem('token')
console.log(token)
if (!noAuth && !token) return <Route path="*" element={<Navigate to="/login" />} />;
return <Route
key={path}
exact={exact}
path={path}
element={<item.component />}
>
{!!children && children.map(i => {
return <Route
key={i.path}
exact={i.exact}
path={i.path}
element={<i.component />}
/>
})}
</Route >;
});
};
const Routers = (props) => {
console.log(props.login, props)
return (
<Router>
<React.Suspense fallback={<Loading />}>
<Routes>
{renderRouter(mainRouteConfig)}
< Route path="*" element={<NotFind to="/login" />} />
</Routes>
</React.Suspense>
</Router>
)
}
export default React.memo(Routers)
import React from 'react'
const App = React.lazy(() => import( "src/App"));
const Login = React.lazy(() => import( "pages/login"));
const System = React.lazy(() => import( "pages/system"));
const Home = React.lazy(() => import( "pages/home"));
export const mainRouteConfig = [
{
path: "/", title: "首页", exact: true, component: App,
children: [
{ path: "/", title: "首页", exact: true, component: Home },
{ path: "/system", title: "系统", exact: true, component: System },
]
},
{ path: "/login", title: "登录", exact: true, component: Login, noAuth: true },
];
五、使用
1.这部分比较简单,在App.js中引入封装好的路由组件并使用。
2.通过 识别路由所对应的组件,整体布局不变,只变中间内容
总结:小编自己写了一套企业管理系统底层模板。地址:githutb
|