如何根据收到的道具使用 React Router 设置动态路由? [英] How to setup dynamic routing with React Router based on props received?

查看:31
本文介绍了如何根据收到的道具使用 React Router 设置动态路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a blogging App in react JS and would like to change the URL path when navigating to a blog article. However, I am running into a problem when using '/:id' in Route with React Router Dom.

导航到这两个 URL 的示例:

Example when navigating to these two URLs:

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}/>

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

With this setup, my blog article is being shown on both the blog article route AND profile route. How do I fix this problem? Is it possible to do render a route like:

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

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

If so how if not what other solutions are there? Please note that due to SEO reasons the blog article title must be shown directly after the first '/' e.g. website.com/blogarticle

非常感谢各位!

亲切的问候,

弗里多

推荐答案

你需要做两个改变:

第一:由于配置文件"是硬编码的,您需要交换顺序并将其放在第一位:

First: As the "profile" is hard-coded, you need to swap the order and put it in first position:

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

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

This way, React Router will first search for those "hard-coded" URLs, and then check the variable ones.

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

Second: You can't have two equal arguments on your URL if they are different (First is a string, probably a slug. Second is an integer). So you will need to modify it as:

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

这可能会奏效!

这篇关于如何根据收到的道具使用 React Router 设置动态路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆