反应路由器和路由参数

时间:2017-01-29 17:47:42

标签: javascript reactjs ecmascript-6 react-router jsx

我已经浏览了一下,我无法找到解决此问题的任何内容。我在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解析为根,因为它认为历史&#39;是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参数的网址不再起作用,并导致循环,因为无论何时尝试渲染,都会失败。

我想知道是否有成语或者有更多反应路由器经验的人可以指出我失踪的明显事物?

1 个答案:

答案 0 :(得分:2)

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

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

/之后不使用test它将成为家庭的可选params

在第1个案例中,只需删除/之后的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>
相关问题