How to setup dynamic routing with React Router based on props received?

允我心安 提交于 2020-04-30 06:32:50

问题


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.

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 setup

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

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

Many thanks guys!

Kind regards,

Frido


回答1:


There are two changes you need to do:

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

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

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

This may do the trick!



来源:https://stackoverflow.com/questions/61319995/how-to-setup-dynamic-routing-with-react-router-based-on-props-received

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!