admin管理员组文章数量:1296401
I'm a bit stuck with the route component. Imagine I have this two Routes with their own path:
<Route path='/person/add' exact component={PersonForm}/>
<Route path='/person/:id' exact component={PersonView}/>
/person/add should show a form where I can create a new Person
/person/:id should show a person with the given id.
The problem >> If I navigate to /person/add it will also show the component of /person/:id because the string "add" is valid for ":id".
Is there a way I can avoid this? For example by telling that :id should be a number?
I'm a bit stuck with the route component. Imagine I have this two Routes with their own path:
<Route path='/person/add' exact component={PersonForm}/>
<Route path='/person/:id' exact component={PersonView}/>
/person/add should show a form where I can create a new Person
/person/:id should show a person with the given id.
The problem >> If I navigate to /person/add it will also show the component of /person/:id because the string "add" is valid for ":id".
Is there a way I can avoid this? For example by telling that :id should be a number?
Share Improve this question edited Dec 7, 2017 at 23:06 Aluan Haddad 31.8k10 gold badges82 silver badges93 bronze badges asked Dec 7, 2017 at 22:49 WannesWannes 1,0692 gold badges11 silver badges21 bronze badges 4 |2 Answers
Reset to default 28Found a possible solution: You can use Switch around the routes. Then it will only match on the first one that matches.
<Switch>
<Route path='/person/add' exact component={PersonForm}/>
<Route path='/person/:id' exact component={PersonView}/>
</Switch>
The problem I was having is that I had several routes;
/locations/:locationId
/locations/new
But when using the matchPath
function from react-router
it would return a false-positive for /locations/:locationId
when I was on /locations/new
. I solved this by passing a custom regex to my identifier;
/locations/:locationId([a-z0-9-]{36})
This will check if my "locationId" is a uuid and otherwise it won't match. It's probably also possible to exclude words like "new/edit/add"
These sources helped me;
- https://github.com/pillarjs/path-to-regexp/tree/v1.7.0#custom-match-parameters
- https://regex101.com/
本文标签: javascriptExclude a value for a path parameter in React Router by typeStack Overflow
版权声明:本文标题:javascript - Exclude a value for a path parameter in React Router by type - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738423308a2085980.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
/person/add
should just be/person
then the state where there is no parameter is the add state and you can reuse it for editing. It makes sense :p – Aluan Haddad Commented Dec 7, 2017 at 22:54