Matching routes with hyphens in react-router

北城余情 提交于 2021-02-08 19:42:06

问题


I have URLs like this;

http://0.0.0.0/country/bosnia-and-herzegovina-644

This is my Route declaration

<Route path="/country/:countrySlug-:countryId" component={CountryPage} />

So this doesnt work as the hyphen breaks it, how can I change it so I only extract the last hyphen as the param, I don't really want to change my slug generation system to use a different character as these are the most readable IMHO, but are only used for information, not content loading.

Thanks


回答1:


I don't know if you can do that, but maybe you could do this:

<Route path="/country/:country" component={CountryPage} />

then in the component:

const countryId = this.props.match.params.country.slice('-').pop();



回答2:


You can't use hyphen - sign for both parameters separation and words separation.

You can use hyphen - for parameters separation and underscore _ for space between countrySlug words.

Here your URL will look like

http://0.0.0.0/country/bosnia_and_herzegovina-644

Now use this Route declaration

<Route path="/country/:countrySlug-:countryId" component={CountryPage} />

When you will generate your link don't forget to replace space with _ sign otherwise your URL will look like this.

http://0.0.0.0/country/bosnia%20and%20herzegovina-644

But still, it will work fine.



来源:https://stackoverflow.com/questions/50088100/matching-routes-with-hyphens-in-react-router

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