1、首先是react-router-dom的安装
npm i --save-dev react-router-dom
2、在src下创建一个router文件夹,创建一个IndexRouter的js文件,在这个文件里面保存路由配置
import React from "react";
import { Navigate, useRoutes } from "react-router-dom";
import NewSandBox from "../views/sandbox/NewSandBox";
export default function IndexRouter() {
const element = useRoutes([
{
path: "/login",
element: Layload("Login/Login"),
},
{
path: "/sandbox",
element: <NewSandBox />,
children: [
{
path: "detail",
element: Layload("sandbox/Detail"),
},
],
},
{
path: "*",
element: Layload("NotFound"),
},
]);
return element;
}
// 路由拦截
function AuthComponent({ children }) {
let token = localStorage.getItem("token");
return token ? children : <Navigate to="/login" />;
}
// 路由懒加载
const Layload = (path) => {
const ComP = React.lazy(() => import(`../views/${path}`));
return (
<React.Suspense fallback={<>加载中...</>}>
<ComP />
</React.Suspense>
);
};
3、在app.js文件里面引入这个文件夹,并且使用
import "./App.css";
import IndexRouter from "./router/IndexRouter";
import { HashRouter } from "react-router-dom";
function App() {
return (
<div className="App">
<HashRouter>
<IndexRouter></IndexRouter>
</HashRouter>
</div>
);
}
export default App;
最后npm start运行项目,就能看到效果啦~
需要注意的是,如果是子组件,需要在父组件加上,才能显示~