代码之家  ›  专栏  ›  技术社区  ›  Velidan

React Router v4-使用更改的默认路由进行动态配置

  •  2
  • Velidan  · 技术社区  · 7 年前

    我现在正在使用React router v4,我希望在一个单独的对象中有一个路由配置,所以我遵循了文档,我做了类似的事情(见下面的代码)

    我想实现这个流程:当用户移动到客户模块时,例如 “/客户” 有应该呈现一个概览组件,然后,我移动路线 “/客户/卡” 仅a卡组件 应该在那里 (概述组件应消失) . 但我不知道我该怎么做。

    我只找到了一种方法来实现它(只需为概览和卡片添加单独的路线。例如 /客户/概述 /客户/卡 .

    但我不想使用此解决方案,因为我想在用户访问“/客户”时准确呈现概述。

    有人能帮我提些建议吗?我会非常合适的。

    以下是最低工作方案的演示: Minimal working demo of the issue

    const routes: any = [
        {
            path : "/",
            component : AsHm,
            exact : true
        },
        {
            path : "/about",
            component : AsAb,
            exact : true
        },
    
        {
            path : "/customer",
            component : AsCus,
            routes : [
                {
                    path : "",
                    component : AsOver,
                    exact: true
                },
                {
                    path : "/customer/cards",
                    component : AsCards,
                    exact: true
                }
            ]
        }
    ];
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Shubham Khatri    7 年前

    没有路径的路由将始终匹配,无论您是否为其指定确切的属性,因此

    {
         path : "",
         component : AsOver,
         exact: true
    },
    

    始终匹配,即使路线是 /customer/cards

    要避免这种情况,您可以使用Switch并在 /客户/卡 . Switch 将渲染第一个匹配的路由,因此使用 path="" 如果 customer/cards 渲染

    所以你的路线看起来像

    const routes: any = [
        {
            path : "/",
            component : Home,
            exact : true
        },
        {
            path : "/about",
            component : About,
            exact : true
        },
        {
            path : "/customer",
            component : Customer,
            routes : [
                {
                    path : "/customer/cards",
                    component : Cards,
                    exact: true
                },
                {
                    path : "",
                    component : Overview,
                    exact: true
                },
            ]
        }
    ];
    

    您的客户组件将如下所示

    const Customer = ({ routes, location })=>(
      <div>
            <h2>Customer Index</h2>
        <Switch>{routes.map((route, i) => <RouteGeneric key={i} {...route} />)}</Switch>
        </div>
    )
    

    Working codepen

    推荐文章