React Router和路由参数

3

我来看了一下,但没有找到能够解决我的问题的内容。我在我的SPA中遇到了一个路由需求问题。URL中间有一个可选参数。例如,我想要这两个URL都有效:

/username/something/overview

并且

/username/overview

为了达到相同的目标。

第一次尝试

我最初尝试使用括号将此标记为可选参数。

<Route path='/:username(/:shard)' component={ProfileContainer}>
  <IndexRoute component={OverviewContainer} />
  <Route component={MatchHistoryContainer} path='/:username/(/:shard)/history' />
  <Route component={DailyTrendsContainer} path='/:username/(/:shard)/trends' />
</Route>

然而,这样做的结果是,username/history会被解析为根目录,因为它认为“history”是shard路由参数的值。因此,username/something/overview可以正常工作,但username/overview不再起作用。 尝试2 我重新定义了一组全新的路由规则。
<Route path='/:username' component={ProfileContainer}>
  <IndexRoute component={OverviewContainer} />
  <Route component={MatchHistoryContainer} path='/:username/history' />
  <Route component={DailyTrendsContainer} path='/:username/trends' />
  <Route path='/:username/:shard' component={ProfileContainer}>
    <IndexRoute component={OverviewContainer} />
    <Route component={MatchHistoryContainer} path='/:username/:shard/history' />
    <Route component={DailyTrendsContainer} path='/:username/:shard/trends' />
  </Route>
</Route>

我将历史和概述路由放在可选参数路由之前,以便它们首先解决。然后,我声明了带有参数的其他路由(但这次没有标记为可选),这样它就会在尝试我想要的路由后解决到那些路由。
通过这种方法,历史和概述都很好用!但是,带有“shard”参数的URL不再起作用,并导致循环,因为每当尝试呈现时,它都失败了。
我想知道是否有一种习语或者有更多react router经验的人可以指出我忽略的明显问题?
1个回答

3

是的,我们可以将可选的 params 放在 URL 的中间,像这样:

<Route path='/test' component={Home}>
    <Route path='/test(/:name)/a' component={Child}/>
</Route>

不要在test后使用“/”,它将成为首页的可选参数。

在您的第一个情况中,只需删除用户名后面的“/”,它应该正常工作,请尝试以下操作:

<Route path='/:username(/:shard)' component={ProfileContainer}>
  <IndexRoute component={OverviewContainer} />
  <Route component={MatchHistoryContainer} path='/:username(/:shard)/history' />
  <Route component={DailyTrendsContainer} path='/:username(/:shard)/trends' />
</Route>

我不确定你是人还是神,但你真的很棒!感谢你发现了我的愚蠢错误!! - christopher
我说得太早了!这意味着如果有可选参数,它将起作用,但如果没有可选参数,它将无法工作。即/:username/history仍然解析为根而不是HistoryContainer。 - christopher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接