我现在正在使用 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>
)
关于reactjs - React Router v4 - 具有更改的默认路由的动态配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49028549/