Parameter passing of routes
There are two ways to pass parameters (it should be noted that both methods are provided in the hook function API, and class components need to be used by higher-order components):
Dynamic routing method;
Search pass parameters (query string);
Method 1: The concept of dynamic routing refers to the path in the routing that is not fixed:
For example, the path of /detail corresponds to a component Detail;
If we write path as /detail/:id when Route matches, then /detail/111 and /detail/123 can match the Route and display it;
We call this matching rule dynamic routing;
Typically, using dynamic routing can pass parameters for the route.
Configure dynamic routing
render() { return ( <div className='app'> <div className='header'> <Link to="detail/123">Details123</Link> <Link to="detail/321">Details321</Link> <Link to="detail/aaa">Detailsaaa</Link> </div> <div className='counter'> <Routes> <Route path='/detail/:id' element={<Detail/>}/> </Routes> </div> <div className='footer'>footer</div> </div> ) }
In the jumped page, you can get the incoming id through the hook function useParms. Since we are now using class components and cannot use hook functions, we need to enhance the current component through higher-order components (I just talked about the encapsulation of higher-order components in the previous article, I will use it directly here and give it to everyone's code)
import { useNavigate, useParams } from "react-router-dom" export default function withRouter(WrapperComponent) { return function(props) { const naviagte = useNavigate() const params = useParams() const router = {naviagte, params} return <WrapperComponent {...props} router={router} /> } }
Use advanced components to enhance the current Detail component, and you can get the passed id through useParams
import React, { PureComponent } from 'react' import withRouter from '../hoc/with_router' export class Detail extends PureComponent { render() { // Get params const { params } = return ( <div> <h2>Detail</h2> {/* Get the id through params and display */} <h2>id: {}</h2> </div> ) } } export default withRouter(Detail)
Method 2: Search passes parameters (that is, the way to query strings), which is demonstrated in the User component here
Query strings on splicing when routing
render() { return ( <div className='app'> <div className='header'> <Link to="/user?name=chenyq&age=18&height=1.88">user</Link> </div> <div className='counter'> <Routes> <Route path='/user' element={<User/>} /> </Routes> </div> <div className='footer'>footer</div> </div> ) }
The query string needs to be obtained through the hook function useSearchParams, so we also need to use higher-order components to enhance the User component.
// Encapsulated high-level components import { useNavigate, useParams, useSearchParams } from "react-router-dom" export default function withRouter(WrapperComponent) { return function(props) { // 1. Navigation const naviagte = useNavigate() // 2. Parameters of dynamic routing const params = useParams() // 3. Query the parameters of the string const [searchParams] = useSearchParams() const query = () const router = {naviagte, params, query} return <WrapperComponent {...props} router={router} /> } }
You can get parameters in the component
import React, { PureComponent } from 'react' import withRouter from '../hoc/with_router' export class User extends PureComponent { render() { // Get query in advanced components const { query } = return ( <div> <h2>User</h2> {/* Get parameters through query */} <h2>parameter: {}-{}-{}</h2> </div> ) } } export default withRouter(User)
Routing configuration file
Currently, all our routing definitions are done directly using the Route component and adding attributes to complete them。
But this method will make routing very confusing. We hope to put all routing configurations into a separate file for centralized management, like vue-router:
In the early days, Router did not provide relevant APIs, we needed to do it with react-router-config;
In this, we are provided with the useRoutes API to complete the relevant configuration;
For example, we configure the following mapping relationship into a separate file
<div className='counter'> <Routes> {/* When the default path /, redirect to the home page */} <Route path='/' element={<Navigate to="/home"/>}></Route> {/* Configure secondary routing */} <Route path='/home' element={<Home/>}> <Route path='/home' element={<Navigate to="/home/recommend"/>}/> <Route path='/home/recommend' element={<HomeRecommend/>}/> <Route path='home/ranking' element={<HomeRanking/>}/> </Route> <Route path='/about' element={<About/>}/> <Route path='/profile' element={<Profile/>}/> <Route path='/category' element={<Category/>}/> <Route path='/order' element={<Order/>}/> <Route path='/detail/:id' element={<Detail/>}/> <Route path='/user' element={<User/>} /> {/* When none of the above paths match, explicit Notfound component */} <Route path='*' element={<Notfound/>}/> </Routes> </div>
First, use the useRoutes API instead of the original Routes and Route components. UseRoutes can be used directly as a function, but can only be used in function components.
<div className='counter'> {useRoutes(routes)} </div>
Then configure the mapping relationship in route/
import { Navigate } from "react-router-dom" import Home from '../pages/Home' import About from '../pages/About' import Profile from '../pages/Profile' import Notfound from '../pages/Notfound' import HomeRecommend from '../pages/HomeRecommend' import HomeRanking from '../pages/HomeRanking' import Category from '../pages/Category' import Order from '../pages/Order' import Detail from '../pages/Detail' import User from '../pages/User' const routes = [ { path: "/", element: <Navigate to="/home"/> }, { path: "/home", element: <Home/>, children: [ { path: "/home", element: <Navigate to="/home/recommend" /> }, { path: "/home/recommend", element: <HomeRecommend/> }, { path: "/home/ranking", element: <HomeRanking/> } ] }, { path: "/about", element: <About/> }, { path: "/profile", element: <Profile/> }, { path: "/category", element: <Category/> }, { path: "/order", element: <Order/> }, { path: "detail/:id", element: <Detail/> }, { path: "/user", element: <User/> }, { path: "*", element: <Notfound/> } ] export default routes
If we load certain components asynchronously (lazy loading, subcontracting) then we need to use Suspense to wrap:
For example, we perform lazy loading (subcontracting processing) on Detail and User
// import Detail from '../pages/Detail' // import User from '../pages/User' const Detail = (() => import("../pages/Detail")) const User = (() => import("../pages/User"))
And you also need to use Suspense to wrap the components
( <HashRouter> <Suspense fallback={<h3>loading</h3>}> <App/> </Suspense> </HashRouter> )
This is the article about the parameter delivery of routes in React - routing configuration files. For more related React routing parameter delivery content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!