【问题标题】:React Router v4 - Dynamic Config with the changed default routeReact Router v4 - 具有更改的默认路由的动态配置
【发布时间】:2018-08-08 06:33:28
【问题描述】:

我现在正在使用 React 路由器 v4,我想在一个单独的对象中拥有一个路由配置,所以我按照文档进行了类似的操作(参见下面的代码)

我想实现这个流程:当用户移动到客户模块时,例如 "/customer" 应该呈现一个概览组件,然后,我移动到路由 " /customer/cards" 只有卡片组件应该在那里(概览组件应该消失)。但我不知道我该怎么做。

我只找到了一种方法来实现它(只需为 Overview 和 Cards 添加单独的路由。例如 /customer/overview/customer/cards

但我不想有这个解决方案,因为我想在用户来到“/customer”时准确地呈现概览。

有人可以帮我提些建议吗?我会很合适的。

这是最小工作方案的演示: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
            }
        ]
    }
];

【问题讨论】:

    标签: reactjs react-router-v4 react-router-dom react-router-component


    【解决方案1】:

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

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

    总是匹配,即使路由是/customer/cards

    你可以做些什么来避免它,是使用 Switch 并在/customer/cards 之后拥有这条路由。 Switch 将渲染第一个匹配的路由,因此如果带有customer/cards 的路由渲染,则不会渲染带有path="" 的路由

    所以你的路线看起来像

    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

    【讨论】:

    • 对,我忘记了 Switch 运算符。谢谢老哥!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    相关资源
    最近更新 更多