【问题标题】:React-Router nested routes namesReact-Router 嵌套路由名称
【发布时间】:2018-02-11 08:19:56
【问题描述】:

我想在 react-router v4 中实现这种路由。

/auth => auth home page    
/auth/login => login page    
/auth/register => register page     
/auth/forgot => lost password page      
/auth/reset => change password page   

它不适用于<Switch>,因为它首先匹配/auth 并渲染关联的组件。因此,当我单击链接转到 login page 时,它会呈现 Auth Component 而不是 Login Component。

如何使用 react-router 实现该行为? 我尝试了嵌套路由,但如果我采用与以前相同的示例,它将呈现Auth Component + Login Component。

谢谢。

【问题讨论】:

    标签: react-router-v4 nested-routes preact


    【解决方案1】:

    您可以将 exact 属性添加到您的 /auth 路由中:

    <Switch>
      <Route exact path='/auth' component={Auth} />
      <Route path='/auth/login' component={Login} />
      <Route path='/auth/register' component={Register} />
      <Route path='/auth/forgot' component={ForgotPassword} />
      <Route path='/auth/reset' component={ChangePassword} />
    </Switch>
    

    或者,您可以将 /auth 路由移到列表末尾,以便其他路由首先匹配:

    <Switch>
      <Route path='/auth/login' component={Login} />
      <Route path='/auth/register' component={Register} />
      <Route path='/auth/forgot' component={ForgotPassword} />
      <Route path='/auth/reset' component={ChangePassword} />
      <Route path='/auth' component={Auth} />
    </Switch>
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 2017-02-03
      • 2017-08-28
      • 2015-02-21
      • 2021-12-30
      • 2020-07-21
      相关资源
      最近更新 更多