React嵌套路由使用

React嵌套路由使用, 一开始想在路由里面嵌套路由,如下:

<Route path="/page1">
    <Route path="/sub1"></Route>
<Route>

一直失败,后面想了个折中的法子,所有路由都配置成同级解析,只是在导航的时候,区分父子节点。

路由配置代码:

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>
)

导航树级结构,根据MyRoutes来生成即可。

猜你喜欢

转载自blog.csdn.net/kaiyuantao/article/details/120268768