React nested routing uses, initially want to nest routing inside the routing, as follows:
<Route path="/page1">
<Route path="/sub1"></Route>
<Route>
It has been failing all the time. Later, I thought of a compromise method. All routes are configured to be parsed at the same level, but the parent and child nodes are distinguished when navigating.
Routing configuration code:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
export const MyRoutes: any[] = [
{
path: "/Page1", name: "Page1",
children: [
{ path: "/Page1-sub1", name: "Page1-sub1", to: Page1-sub1},
{ path: "/Page1-sub2", name: "Page1-sub2", to: Page1-sub2},],
},
]
const allPath = () => {
let paths = MyRoutes;
MyRoutes.forEach((item: any) => {
if (item.children !== undefined && item.children.length > 0) {
paths = [...paths, ...item.children]
}
})
return paths;
}
const RouterMap = () => (
<div>
<Switch>
{allPath().map(item => {
return <Route key={item.path} exact={true} path={item.path} component={item.to} />
})}
</Switch>
</div>
)
The navigation tree structure can be generated according to MyRoutes.