React Router 使用 /:username 或 /component/ 渲染组件



我正在尝试实现一种路由结构,当路径为/:username 时,用户将转到另一个用户的页面或他们自己的页面。我还想渲染另一个带有路径/watch 或/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} />
}
}} />

现在,如果我到了/watch/配置文件组件也会被渲染。所以 :用户名会匹配我的所有路线吗?

正如您已经推断的那样,/:username/watch/同时匹配,因为两种模式都与 URL/watch/匹配。

值得庆幸的是,React Router 为像这样的情况提供了一个<Switch>组件,其中只呈现第一个匹配项:

<Switch>
<Route path="/watch/" component={Watch} />
<Route path="/:username" component={...} />
</Switch>

现在,使用 URL/watch/,仅呈现第一个路由,即使第二个路由也匹配。

如果您使用的是react-router-dom v6,请执行以下操作:

  1. 而不是Switch,你应该使用Routes
  2. 使用element={<SomeComponent />}而不是component={<SomeComponent />}属性

以防万一,您可以阅读这篇关于从 v5 升级到 v6 的文章

相关内容