简体   繁体   中英

How to make same URL scheme but different route and component in React JS

I have some dynamic and static URLS, I am ibiut but confused how to call different component on same route structure, pleas have a look below

**Required Routes structure: **

https://example.com/:pagename (dynamic)
https://example.com/:countryname (dynamic)

https://example.com/about-us (static)

Current Route:

<Route path='/:pageName' component={Page} exact />
<Route path='/:countryname' component={Country} exact />
<Route path='/about-us' component={AboutUs} exact />

Thanks

The better way to do this is to change your URL logic as follows:

https://example.com/page/:pagename or https://example.com/p/:pagename

https://example.com/country/:countryname or https://example.com/c/:countryname

and the Routes:

<Route path='/page/:pageName' component={Page} exact />
<Route path='/country/:countryname' component={Country} exact />

The Route algorithm stops at the first URL-pattern that matches the query. Consider the following two URLs:

Both of these URLs match the first pattern ( https://example.com/:pagename ) as the matching algorithm won't know that "germany" is not a pagename.

If you can't go this way you could build a sub-routing component which checks whether the first parameters after example.com matches any country name or any page name and based on that render the corresponding component:

    <Route path='/:pageNameOrCountryNameNotSure' component={SubRouter} exact />

However, this is not a clean solution and is not recommended .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM