reactjs - React Router v4 - 具有更改的默认路由的动态配置

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

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

我想实现这个流程:当用户移动到客户模块时,例如“/customer”,应该呈现一个概述组件,之后,我移动到路线“/customer/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
            }
        ]
    }
];

最佳答案

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

{
     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

关于reactjs - React Router v4 - 具有更改的默认路由的动态配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49028549/

相关文章:

reactjs - 在 react 中使用 <Link> 将对象数组传递给另一个组件

javascript - React-Router v4 问题 - URL 更新但组件未重新渲染

javascript - React-router:一旦安装了路由上的组件,即使路由发生变化,也永远不会卸载

javascript - 如何处理从 Node Express 重定向到 React Client 的身份验证(react-router-dom 和 useContext)

reactjs - 使用 useRouteMatch 时从 React router dom v5 转换为 React router dom v6

reactjs - react-admin:如果将 react-admin 嵌入到非 redux 应用程序中,是否需要将 redux 安装到应用程序中?

javascript - 在 Vercel 上部署 React 应用程序后出现空白屏幕

javascript - 更改 google-maps-react 上选定多边形的颜色

reactjs - 任何人都可以与护照谷歌 oauth2 集成分享下一个 js 的例子吗?

javascript - 使用 withRouter() 重定向时显示所有组件