[英]How to access different components by routes with slug only in react-router-dom?
Lets say we have two components for Post and Project. 可以说我们有两个用于Post和Project的组件。 Each post and project has slug.
每个职位和项目都有。 I want to access post and projects by slug.
我想通过子弹访问帖子和项目。 So we have routes:
所以我们有路线:
<Route path="/:post_slug" component={PostComponent} />
<Route path="/:project_slug" component={ProjectComponent} />
And for example when you visit some post pr project, an action gets called to fetch its data by params. 例如,当您访问某个后期项目时,将调用一个操作以通过参数获取其数据。 Something like this:
像这样:
this.props.fetchPost(this.props.match.params.post_slug)
this.props.fetchProject(this.props.match.params.project_slug)
If I do only one component accessible by slug only, then it works. 如果我只执行一个只能通过子段访问的组件,则它可以工作。 But if I want to access two different components by slug, then it's messed up.
但是,如果我想通过访问来访问两个不同的组件,那就搞砸了。 And ie when I visit post, react thinks that I'm visiting project.
即,当我访问帖子时,React认为我正在访问项目。
Maybe there is some way to handle such case in react-router-dom? 在react-router-dom中也许有某种方法可以处理这种情况?
There is no way to do this, since the router can't differentiate between the two routes. 无法执行此操作,因为路由器无法区分两条路由。 For example, if I were to navigate to
site.com/my_slug
, the router wouldn't know whether my_slug
is supposed to be a :post_slug
or a :project_slug
. 例如,如果我要导航到
site.com/my_slug
,路由器将不知道my_slug
应该是:post_slug
还是:project_slug
。 It's sending you to a project when they're both present because it interprets them to be the same route and so it uses the last one you define. 当它们都存在时,它将把您发送到一个项目,因为它将它们解释为相同的路线,因此它使用您定义的最后一条路线。
An alternative you could try is being a bit more explicit with your routes, like so: 您可以尝试的替代方法是对路由进行更明确的显示,例如:
<Route path="/post/:post_slug" component={PostComponent} />
<Route path="/project/:project_slug" component={ProjectComponent} />
You could do this if you put the detection logic in another component, like this: 如果将检测逻辑放在另一个组件中,则可以执行以下操作:
<Route path="/:any_slug" component={AnyComponent} />
Then let that component figure out what type of ID you have and render the desired sub-component accordingly: 然后,让该组件找出您拥有的ID类型,并相应地呈现所需的子组件:
const AnyComponent = props => {
if (slugIsProject(props.match.params.any_slug)) {
return <ProjectComponent id={props.match.params.any_slug} />;
} else {
return <PostComponent id={props.match.params.any_slug} />;
}
}
This way the router always renders the same component ( AnyComponent
) but that component appears differently depending on what the ID is determined to be. 这样,路由器始终呈现相同的组件(
AnyComponent
),但是该组件根据ID确定为不同而呈现不同的外观。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.