React Router:从通用的' /:slug '路径中排除字符串



我正在尝试基于路由设置以下UI

  • /things/-显示项目列表(组件A)
  • /things/new-显示项目列表,具有模态形式叠加(组件a和组件B)
  • /things/:slug-显示特定项(组件C)

这样设置:

  • /things/显示组件A
  • /things/new将显示组件A和组件B
  • /things/:slug只显示组件C

这些都在一个嵌套的路由-/things中。这意味着pathuseRouteMatch返回/things

我已经尝试了Switch的几个组合,并试图使用matchPathuseRouteMatch来区分/new/:slug,但没有运气。每次尝试都会导致其中一个路径没有返回正确的组件。

例如:

<Switch>
<Route path="/:slug(exclude "new")" exact component={ComponentC} />
<Route path="/" exact component={ComponentA} />
</Switch>
<Route path="/new" component={ComponentB} />

我尝试过的另一个没有运气的选择是在鼻涕虫上使用正则表达式,以匹配鼻涕虫模式。让我们说弹头图案是xxx-xxx-xxx-###,然后我尝试:

<Route path="/:slug((w*-)*(d*))" component={ComponentC) />

但由于某些原因,这与路由不匹配。

我想我可以使用location.pathname,但这似乎是一个hack。

是否有可能匹配和渲染路由如上所述的标准<Route path="[something]" />组件与此设置?

这就是我喜欢Stack Overflow的原因。问问题往往会引出你自己的答案。

我正在浏览React Router文档中的regex信息,发现Routepath属性可以接受路径数组。所以我选择了这个:

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>