[英]React Router: Exclude strings from generic `/:slug` path
I'm attempting to setup the following UI based on routes我正在尝试根据路由设置以下 UI
/things/
- display the list of items (Component A) /things/
- 显示项目列表(组件 A)/things/new
- display the list of items, with a modal form overlay (Component A and Component B) /things/new
- 显示项目列表,带有模态表单覆盖(组件 A 和组件 B)/things/:slug
- display a specific item (Component C) /things/:slug
- 显示特定项目(组件 C)With this setup:使用此设置:
/things/
would display Component A /things/
将显示组件 A/things/new
would display Component A AND Component B /things/new
将显示组件 A 和组件 B/things/:slug
would display ONLY Component C /things/:slug
将只显示组件 C This is all in a nested route - /things
.这一切都在嵌套路由中 - /things
。 Which means the path
from useRouteMatch
returns /things
这意味着useRouteMatch
的path
返回/things
I have tried several combos with Switch
, and attempted to use matchPath
and useRouteMatch
to differentiate /new
from /:slug
but with no luck.我尝试了多个Switch
组合,并尝试使用matchPath
和useRouteMatch
来区分/new
和/:slug
但没有成功。 Every attempt results in one of the paths not returning the correct component.每次尝试都会导致其中一个路径没有返回正确的组件。
For example:例如:
<Switch>
<Route path="/:slug(exclude "new")" exact component={ComponentC} />
<Route path="/" exact component={ComponentA} />
</Switch>
<Route path="/new" component={ComponentB} />
Another option I've tried with no luck is to use regex on the slug, to match the slug pattern.我尝试过但没有运气的另一个选择是在 slug 上使用正则表达式,以匹配 slug 模式。 Let's says the slug pattern is xxx-xxx-xxx-###
, then I tried:假设 slug 模式是xxx-xxx-xxx-###
,然后我试过:
<Route path="/:slug((\w*-)*(\d*))" component={ComponentC) />
but this doesn't match the routes for some reason.但这由于某种原因与路线不匹配。
I'm thinking I could use location.pathname
but this seems like a hack.我想我可以使用location.pathname
但这似乎是一个黑客。
Is it possible to match and render routes as described above with standard <Route path="[something]" />
components with this setup?是否可以使用此设置与标准<Route path="[something]" />
组件匹配和呈现上述<Route path="[something]" />
?
This is why I love Stack Overflow.这就是我喜欢 Stack Overflow 的原因。 Asking the question often leads you to answer it yourself.问这个问题通常会让你自己回答。
I was browsing the React Router docs for info on the regex and discovered the Route
path
property can accept an array of paths.我正在浏览 React Router 文档以获取有关正则表达式的信息,并发现Route
path
属性可以接受一系列路径。 So I went with this:所以我去了这个:
const { path } = useRouteMatch()
<Route path={[path, `${path}/new`]} exact component={ThingsList} />
<Switch>
<Route path={`${path}/new`} render={() => <NewThing path={path} />} />
<Route path={`${path}/:slug`} render={() => <Thing path={path} />} />
</Switch>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.