在React Router中,如何使用不同的参数路由到2个类似的URL

时间:2016-01-28 03:19:06

标签: javascript reactjs react-router

例如,我有一条播放歌曲的<Song />路线,我希望另一条路线<SongInfo />显示该歌曲的信息,另一条<SongComments />显示评论。

<Route path="songs" component={Songs} />
<Route path="song/:id/:name" component={Song} />
<Route path="songs/:id/:name/:info" component={SongInfo} />
<Route path="songs/:id/:name/:comments" component={SongComments} />

我希望网址结构如下所示:

/songs/123/cool_song/
/songs/123/cool_song/info
/songs/123/cool_song/comments

我如何实现这一目标?目前最后两条路线是相同的,并转到相同的组件。

我正在使用react-router: 1.0.0

1 个答案:

答案 0 :(得分:1)

Numinfo是静态字还是变量?我问,因为在路由中你将它们用作变量,但在例子中你将它们用作静态字。 如果它们永远不会改变,那么您的路线应该如下:

comments

(我在信息和评论之前删除了冒号)。现在,如果您有网址<Route path="songs" component={Songs} /> <Route path="song/:id/:name" component={Song} /> <Route path="songs/:id/:name/info" component={SongInfo} /> <Route path="songs/:id/:name/comments" component={SongComments} /> ,它将运行/songs/123/cool_song/info组件。如果您有网址SongInfo,则会运行/songs/123/cool_song/comments

但是如果信息和注释是将被某些字符串替换的变量,则问题在于最后两个路由器是否相同。即使人类必须决定,例如SongComments/songs/123/cool_song/great-song是评论还是信息?你必须使它们与众不同。例如:

great-song

您的网址会显示:

<Route path="songs" component={Songs} />
<Route path="song/:id/:name" component={Song} />
<Route path="songs/:id/:name/i/:info" component={SongInfo} />
<Route path="songs/:id/:name/c/:comments" component={SongComments} />