In the current project, it is recommended to use routing table configuration to register routes
Install the routing plugin library
The first step, we need to install the routing plugin in the project
yarn add react-router-dom
Global Router Management
The following files are index.js in the root directory built using scaffolding
src/index.js
Use the BrowserRouter based on the history mode to wrap the app component; of course, you can also use the HashRouter wrap (hash routing)
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
reportWebVitals();
routing table
In project development, we don't write the routing table chaotically on the page, so it is recommended to put it in a unified file for management
Among them, we also need to use lazy loading lazy and callback component method Suspense when the network is abnormal
For example: src/routes/index.js
/* eslint-disable import/no-anonymous-default-export */
import React, { lazy, Suspense } from "react";
import { Navigate } from "react-router-dom";
import NotFound from "../pages/NotFound";
function lazyLoad(path) {
const Comp = lazy(() => import("../pages/homepage/components/" + path));
return (
<Suspense fallback={<div>加载中……</div>}>
<Comp />
</Suspense>
);
}
export default [
{
path: "/about",
element: lazyLoad("About"),
},
{
path: "/home",
element: lazyLoad("Home"),
children: [
{
path: "news",
element: lazyLoad("News"),
},
{
path: "message",
element: lazyLoad("Message"),
},
],
},
{
path: "/",
element: <Navigate to="/home" />,
},
{
path: "*",
element: <NotFound />,
},
];
register route
Register with useRoutes, register in pages that use route navigation
import React, { Fragment } from "react";
import { NavLink, useRoutes } from "react-router-dom";
import routes from "../../routes";
import "./index.css";
export default function Homepage() {
function classNameActive({ isActive }) {
return isActive ? "nav blue" : "nav";
}
const element = useRoutes(routes);
return (
<Fragment>
<NavLink className={classNameActive} to="./about">
about
</NavLink>
<br />
<NavLink className={classNameActive} to="./home">
home
</NavLink>
<br />
{element}
</Fragment>
);
}
Mount the page content corresponding to the secondary route
The first-level route presents the content of the second-level route, which needs to be mounted by introducing the Outlet component
import React, { Fragment } from "react";
import { Outlet, NavLink } from "react-router-dom";
export default function index() {
return (
<Fragment>
home组件
<hr />
<NavLink to="news">News</NavLink>
<br />
<NavLink to="message">Messagee</NavLink>
//指定路由组件内容呈现的位置
<Outlet />
</Fragment>
);
}