前言
本章主要讲路由配置以及使用useRoutes生成路由规则展示路由页面
一、在根目录配置路由
注:layout布局组件后续会单独讲
// @/router/index.js
import { Navigate } from "react-router-dom"; // 路由重定向函数 Navigate
import Layout from "@/layout";
import Login from "@/pages/login";
import Workbench from "@/pages/workbench";
import CustomerList from "@/pages/customerList";
import ChainManage from "@/pages/chainManage";
import NotFound from "@/pages/notFound";
import Auth from "@/components/auth";
const routes = [
{
path: "/layout",
element: (
<Auth>
<Layout />
</Auth>
),
children: [
{ path: "/layout/Workbench", element: <Workbench /> },
{ path: "/layout/chainManage", element: <ChainManage /> },
{ path: "/layout/customerManage", element: <TodoList /> },
{
path: "*",
element: <NotFound />,
},
],
},
{
path: "/login",
element: <Login />,
},
{
path: "",
element: <Navigate to="/layout/Workbench" />,
}
];
export default routes;
二、Auth权限组件封装
// @/components/auth/index.jsx
import { getToken } from "@/utils/storage";
import { Navigate } from "react-router-dom";
const Auth = ({ children }) => {
const isToken = getToken();
// 判断token是否存在,如果存在正常渲染,如果不存在重定向到登录路由
if (isToken) {
return <>{children}</>;
} else {
return <Navigate to="/login" replace />;
}
};
export default Auth;
三、在App.js中引入,并使用useRoutes展示路由页面
// @/App.js
import "./App.css";
import { useRoutes } from "react-router-dom";
import routes from "./router";
function App() {
const element = useRoutes(routes); // 生成路由规则
return (
<div className="App">
{element} {/* 展示区 */}
</div>
);
}
export default App;
总结
下一篇讲【使用Error Boundary捕捉错误边界】。关注本栏目,会实时更新!