There are a variety of ways to implement route nesting on the web. Router-dom3. X and react-router-dom3.

Here are my react and react-router-dom versions:

"React" : "^ 17.0.2", "the react - the router - dom" : "^ 5.2.0",Copy the code

As required, we need to separate the routing configuration into a JS file and expose it:

/router/routerList.js

import { lazy } from 'react'; Const routerList = [{path: "/", // path name: "home ", // name: true, // Exact match component: Lazy (() => import('../page/main/index'))}, {path: "/user", name: "user management ", exact: true, component: Lazy (() => import('../page/user/index')), routes: [{path: "/user/userList", name: "user list ", exact: true, component: Lazy (() = > import ('.. / page/user/userList/index ')), routes: [{path: "/ user/userList/userDetail," name: "user details", exact: true, component: lazy(() => import('../page/user/userList/userDetail/index')), } ] } ] } ] export default routerList;Copy the code

Here I use react lazy loading to speed up loading.

React-router-dom5.x nesting scheme

/router/index.js

import { BrowserRouter, Route, Switch } from 'react-router-dom'; import React, { Suspense, Fragment } from 'react'; import routerList from './routerList'; Class CustomRoute extends React.Component {// Recursive method routerListRecursion = (routerList) => {return Object.assign(routerList).map(({ path, exact, routes, component: LazyComponent }, key) => { let newItem = { path, exact, routes }; if (routes && routes.length) { return ( <Fragment key={`fragment${key}`}> <Route key={key} {... newItem} render={(props) => <LazyComponent {... Render <Switch key={' Switch ${key} '}> {this.routerListRecursion(routes)} </Switch> </Fragment> ) } else { return <Route key={key} {... newItem} render={(props) => <LazyComponent {... props} />}></Route> } }) } render() { return ( <BrowserRouter> <Suspense fallback={<span>Loading... </span> {routerListRecursion(routerList)}} {{component.routerListrecursion (routerList)}} </BrowserRouter> ); } } export default CustomRoute;Copy the code

This implements a route nesting based on react-router-dom 5.x, and writes the CustomRouter component to the main entry:

index.js

import ReactDOM from 'react-dom';
import CustomRoute from './router/index';

ReactDOM.render(
  <CustomRoute/>,
  document.getElementById('root')
);
Copy the code

Reference: blog.csdn.net/Vue2018/art…

I React small white a piece, if there is a problem with the code, there is a problem that can be optimized, there is a problem with the idea, please leave a comment together to discuss, thank you!!