reactjs - 如何根据收到的道具使用 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
非常感谢你们!
亲切的问候,
弗里多
解决方案
您需要进行两项更改:
第一:由于“配置文件”是硬编码的,您需要交换订单并将其放在第一位:
<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} />
这可能会奏效!
推荐阅读
- asp.net - 如何检查用户是否打开特定页面
- python - 计算熊猫 df col 中子字符串列表的出现次数
- python - 如何匹配数据框中的相反值?
- c# - 更改每个 3D 游戏对象的材质
- mysql - 在带有定义值的 Phpmyadmin 中使用命令将新列添加到表结构
- r - 如何使用shinyjs从闪亮的应用程序物理打印png?
- c# - 如何将事件处理程序添加一个 DLL 编译按钮从一个 WPF 项目到另一个?
- swift - 当 tableView 单元格从 scrollView 中间经过时添加调光视图
- webpack - 如何设置 laravel mix 以动态导入子目录中的项目
- python - if 语句中带有双引号的语法错误