【问题标题】:React Router render components with /:username or /component/React Router 使用 /:username 或 /component/ 渲染组件
【发布时间】:2018-08-29 20:24:33
【问题描述】:

我正在尝试实现一个路由结构,当路径为 /:username 时,用户可以转到另一个用户的页面或他们自己的页面。我还想用路径 /watch 或 /watch/ 呈现另一个页面。Facebook 有类似的设置,其中 /:username 会将您带到您的页面或其他用户的页面,而 /watch/ 例如是一个页面。是否有使用 react-router 实现这一目标的最佳实践?

到目前为止,我有这样的东西..

<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 会匹配我所有的路由吗?

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

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

    谢天谢地,React Router 为这种情况提供了 &lt;Switch&gt; component,其中仅呈现 第一个匹配项

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

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

    【讨论】:

      【解决方案2】:

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

      1. 而不是Switch,您应该使用Routes
      2. 而不是component={&lt;SomeComponent /&gt;} 属性,使用element={&lt;SomeComponent /&gt;}

      以防万一,你可以Read this article about upgrading from v5 to v6

      【讨论】:

        猜你喜欢
        • 2018-01-07
        • 1970-01-01
        • 2018-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-14
        相关资源
        最近更新 更多