React Router 和路由参数

React Router and route params

我浏览了一下,但找不到任何可以解决此问题的方法。我的 SPA 中存在路由要求问题。 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>

我将 historyoverview 路由放在带有可选参数的路由之上,以便它们首先解析。然后我用参数声明了额外的路由(但这次没有标记为可选)所以它会在它尝试了我想要的那些之后解析到那些。

通过这种方法,历史概览 大有作为!但是,其中带有 shard 参数的 url 不再有效,并导致循环,因为每当它尝试渲染时,它都会失败。

我想知道是否有成语或者对 React 路由器有更多经验的人可以指出一些明显的我遗漏的东西?

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

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

不要在 test 之后使用 / 它将成为主页的可选 params

在你的第一种情况下,只需删除 username 之后的 /,它应该可以工作,试试这个:

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