react-router
React-router-dom V6 has a much better overall experience than V5. One of the biggest changes is that the Route configuration cannot be nested, and the entire Route configuration must be broken up into several pieces, except with a plugin like react-router-config. You can manage the entire route, but now you don’t need any plug-ins to manage the route configuration.
React-router
React-router-dom-v6-example: react-router-dom-v6-example
v6
与 v5
The difference between
The current environment
- The installation
npm install --save react-router-dom history
Copy the code
react
.react-router-dom
And related plug-in versions.
"dependencies": {
"history": "^ 5.1.0"."react": "^ 17.0.2"."react-dom": "^ 17.0.2"."react-router-dom": "^ 6.0.2." "
}
Copy the code
- If you pass by yourself
webpack
Configure the project, be sure to be indevServe
To addhistoryApiFallback: true
To solvehistory
The mode page appears after refreshing404
In the case.
devServer: {
port,
host,
hot: true.open: true.historyApiFallback: {disableDotRule: true}},// And publicPath in 'output'
output: {
path: path.resolve(__dirname, ".. /dist"),
filename: "[name].[chunkhash].js".publicPath: '/'
},
Copy the code
use
Render router.tsx directly in the entry file
// idex.tsx
import React from "react";
import ReactDOM from "react-dom";
import Router from "./router/Router";
import "./index";
ReactDOM.render(<Router />.document.getElementById("root"));
Copy the code
1. Routes
Component replacementv5
的 Switch
Components;
The Route component must be nested with Routes
// Router.tsx
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from ".. /home/Home";
import Goods from ".. /goods/Goods";
import Customer from ".. /customer/Customer";
export default function Router() {{/* All routing configurations are inside BrowserRouter */}
return (
<BrowserRouter>{/* replace old Switch */}<Routes>
<Route path='/' element={<Home />} / ><Route path='goods' element={<Goods />} / ><Route path='customer' element={<Customer />} / ></Routes>
</BrowserRouter>
);
}
Copy the code
2. Jump
- through
Link
Component jump;
// Customer.tsx
import React from "react";
import { Link } from "react-router-dom";
export default function Customer() {
return (
<div>
<h2>Customer Page</h2>
<Link to="/goods"> to Goods</Link>
</div>
);
}
Copy the code
- through
useNavigate
Method jump;
// Goods.tsx
import React from "react";
import { useNavigate } from "react-router-dom";
export default function Goods() {
const navigate = useNavigate();
const handleClickToHome = () = > {
navigate("/");
// Replace mode for history
// navigate("/", { replace: true });
};
return (
<div>
<h2>Goods Page</h2>
<button onClick={handleClickToHome}>to Home</button>
</div>
);
}
Copy the code
3. Match the route that is not defined
V6 removes the Redirect component.
// Router.tsx
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from ".. /home/Home";
import Goods from ".. /goods/Goods";
import Customer from ".. /customer/Customer";
import NotFound from ".. /not-found/NotFound";
export default function Router() {{/* All routing configurations are inside BrowserRouter */ }
return (
<BrowserRouter>{/* replace old Switch */}<Routes>
<Route path='/' element={<Home />} / ><Route path='goods' element={<Goods />} / ><Route path='customer' element={<Customer />} /> {/* Matches undefined routes */}<Route path="*" element={<NotFound />} / ></Routes>
</BrowserRouter>
);
}
Copy the code
4. Nested route and dynamic route
- Set set by
path
Can not write the parent, will be directly spliced; - Dynamic Routing through
:style
Form realization; - Due to the
/goods/list
Is greater than/goods/*
Therefore, if you enter the exact address, the route will be matched precisely instead of the dynamic route. - Nested routines must be appended at the parent level
Outlet
Component, as a placeholder for a child component, similar tovue-router
In therouter-view
。
// Router.tsx
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from ".. /home/Home";
import Goods from ".. /goods/Goods";
import Customer from ".. /customer/Customer";
import NotFound from ".. /not-found/NotFound";
import GoodsDetail from ".. /goods/goods-detail/GoodsDetail";
import GoodsList from ".. /goods/goods-list/GoodsList";
export default function Router() {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={<Home />} ><Route path='goods' element={<Goods />} > {/* Dynamic routing */}<Route path=":id" element={<GoodsDetail />} / ><Route path="list" element={<GoodsList />} / ></Route>
<Route path='customer' element={<Customer />} ></Route>
</Route>
<Route path="*" element={<NotFound />} / ></Routes>
</BrowserRouter>
);
}
// Home.tsx
import React from "react";
import { Outlet, Link } from "react-router-dom";
export default function Home() {
return (
<div>
<h1>Home</h1>
<p>
<Link to='/goods'>to goods</Link>
</p>
<p>
<Link to='/customer'>to customer</Link>
</p>
<Outlet />
</div>
);
}
// Goods.tsx
import React from "react";
import { useNavigate, Outlet } from "react-router-dom";
export default function Goods() {
const navigate = useNavigate();
const handleClickToHome = () = > {
navigate("/");
// Replace mode for history
// navigate("/", { replace: true });
};
return (
<div>
<h2>Goods Page</h2>
<button onClick={handleClickToHome}>to Home</button>{/* Placeholders for child routing */}<Outlet />
</div>
);
}
Copy the code
5. Obtain route parameters
useParams
Get the value of the dynamic route.useSearchParams
Gets the value of the query string.
// GoodsDetail.tsx
import React,{ useEffect } from "react";
import { useParams, useSearchParams } from "react-router-dom";
export default function GoodsDetail() {
// Get the value of the dynamic route
const params = useParams();
// Get the value of the query string
const [searchParams, setSearchParams] = useSearchParams();
useEffect(() = > {
// An object whose key is the key of a dynamic string
console.log(params); // {id: '123'}
// An object, but not a property
console.log(typeof searchParams); // object
/ / http://localhost:3304/goods/123? name=nihao
console.log(searchParams.get("name")); // nihao} []);const handleAddParams = () = > {
// Modify the query string data
setSearchParams({
name:"xxx"
});
};
return (
<div>
<h2 onClick={handleAddParams}>GoodsDetail Page</h2>
</div>
);
}
Copy the code
6. Default route
When the page has multiple child routes, such as /goods, the page displays a list of goods. /goods/: ID displays the details of a product.
Route
的index
Property is used to show the default child path.
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from ".. /home/Home";
import Goods from ".. /goods/Goods";
import Customer from ".. /customer/Customer";
import NotFound from ".. /not-found/NotFound";
import GoodsDetail from ".. /goods/goods-detail/GoodsDetail";
import GoodsList from ".. /goods/goods-list/GoodsList";
export default function Router() {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={<Home />} ><Route path='goods' element={<Goods />} > {/* The default route is /goods, which will be displayed on the page */}<Route index element={<GoodsList />} / ><Route path=":id" element={<GoodsDetail />} / ></Route>
<Route path='customer' element={<Customer />} ></Route>
<Route path="*" element={<NotFound />} / ></Route>
</Routes>
</BrowserRouter>
);
}
Copy the code
7. Configure route management
UseRoutes can route the array object directly to the page.
// Entry file, SRC /index.tsx
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import "./index";
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById("root"));
// src/router/routes.tsx
import React from "react";
import { RouteObject } from "react-router-dom";
import Home from ".. /home/Home";
import Goods from ".. /goods/Goods";
import Customer from ".. /customer/Customer";
import NotFound from ".. /not-found/NotFound";
import GoodsDetail from ".. /goods/goods-detail/GoodsDetail";
import GoodsList from ".. /goods/goods-list/GoodsList";
const routes: RouteObject[] = [
{
path: "/".element: <Home />,
children: [
{
path: "/goods".element: <Goods />,
children: [
{ index: true.element: <GoodsList /> },
{ path: ":id".element: <GoodsDetail />}]}, {path: "/customer".element: <Customer />}, {path: "*".element: <NotFound />,},]}];export default routes;
// src/App.tsx
import React from "react";
import { useRoutes } from "react-router-dom";
import routes from "./router/routes";
export default function App() {
const element = useRoutes(routes);
return (
<>
{element}
</>
);
}
Copy the code