【发布时间】:2017-06-14 21:48:15
【问题描述】:
我浏览了一遍,但找不到任何可以解决这个问题的方法。我的 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 解析为根,因为它认为“历史”是 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>
我将 history 和 overview 路由放在带有可选参数的路由之上,以便它们首先解析。然后我用参数声明了额外的路由(但这次没有标记为可选),所以它会在尝试了我想要的路由后解决这些路由。
通过这种方法,history 和 overview 非常有用!但是,其中带有 shard 参数的 url 不再起作用,并导致循环,因为每当它尝试渲染时,它都会失败。
我想知道是否有一个成语或对反应路由器有更多经验的人可以指出我明显遗漏的东西?
【问题讨论】:
标签: javascript reactjs ecmascript-6 react-router jsx