首页 > 解决方案 > 如何根据收到的道具使用 React Router 设置动态路由?

问题描述

我在 react JS 中创建了一个博客应用程序,并希望在导航到博客文章时更改 URL 路径。但是,在带有 React Router Dom 的 Route 中使用 '/:id' 时遇到了问题。

导航到这两个 URL 时的示例:

Blog article URL:
https://website.com/myfirstblogpost/4582819

Profile page URL:
https://website.com/profile/902310

App.js 设置

<Route path="/:id/:id" component={BlogArticle} exact={true} />
<Route path="/profile/:id" component={Profile} exact={true}/>

使用此设置,我的博客文章将同时显示在博客文章路由和个人资料路由上。我该如何解决这个问题?是否可以渲染如下路线:

<Route path=`{/${blog.title}/${blog.id}}` component={BlogArticle} exact={true} />
<Route path=`{/profile/${user.id}`component={Profile} exact={true}/>

如果是这样,如果不是,还有什么其他解决方案?请注意,由于 SEO 原因,博客文章标题必须直接显示在第一个“/”之后,例如 website.com/blogarticle

非常感谢你们!

亲切的问候,

弗里多

标签: reactjsreact-router

解决方案


您需要进行两项更改:

第一:由于“配置文件”是硬编码的,您需要交换订单并将其放在第一位:

<Route path="/profile/:id" component={Profile} exact={true}/>
<Route path="/:id/:id" component={BlogArticle} exact={true} />

这样,React Router 将首先搜索那些“硬编码”的 URL,然后检查可变的 URL。

第二:如果它们不同,则您的 URL 不能有两个相等的参数(第一个是字符串,可能是 slug。第二个是整数)。因此,您需要将其修改为:

<Route path="/profile/:id" component={Profile} exact={true}/>
<Route path="/:title/:id" component={BlogArticle} exact={true} />

这可能会奏效!


推荐阅读