我正在尝试实现一种路由结构,当路径为/:username时,用户会转到另一个用户的页面或他们自己的页面。我还想渲染另一个带有路径/手表或/ watch /的页面.Facebook有类似的设置,其中/:用户名将带您到您的页面或其他用户和/ watch /例如是一个页面。有反应路由器实现这一目标的最佳做法吗?
截至目前我有类似的东西..
<Route path="/" exact component={authenticated ? Home : Index} />
<Route path="/watch/" component={Watch} />
<Route path="/:username" exact component={({match}) => {
if(match.params.username === data.Username) {
return <ProfilePage match={match} />
} else {
return <UserPage match={match} />
}
}} />
现在,如果我到/观察/配置文件组件正在渲染。所以:用户名将匹配我的所有路线?
正如您已经推断的那样,/:username
与/watch/
同时匹配,因为两种模式都与URL /watch/
匹配。
值得庆幸的是,React Router为像这样的情况提供了<Switch>
component,其中只渲染了第一个匹配:
<Switch>
<Route path="/watch/" component={Watch} />
<Route path="/:username" component={...} />
</Switch>
现在,使用URL /watch/
,只渲染第一条路线,即使第二条路线也匹配。