我现在正在使用React路由器v4,我希望在一个单独的对象中有一个route-config,所以我按照文档说明我做了类似的事情(见下面的代码)
我想实现这个流程:当用户移动到客户模块,例如“/ customer”时,应该呈现一个Overview组件,之后,我移动路径“/ customer / cards”,只有一个Cards组件应该在那里(Overview组件应该消失)。但我无法弄清楚我是怎么做到的。
我发现只有一种方法可以实现它(只需添加概述和卡片的分离路线。例如/客户/概述和/客户/卡。
但我不想拥有这个解决方案,因为我想在用户访问“/ 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
将渲染第一个匹配的路线,因此如果使用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>
)