使用反应路由器布局路线 [英] Layout routes with react router

查看:37
本文介绍了使用反应路由器布局路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 react-router 进行布局.

当我的用户点击 / 我想呈现一些布局.当我的用户点击 /login/sign_up 时,我希望使用 /login/的相关组件呈现布局sign_up 呈现.

目前,我的 App.js 看起来像这样

返回 (

<Route path="/" component={Auth}/><ModalContainer/>

);

我的 Auth.js 看起来像这样

返回 (<AuthFrame footerText={footerText} footerClick={footerClick}><Route path="/login" component={LoginContainer}/><Route path="/sign_up" component={SignUpContainer}/></AuthFrame>);

所以 AuthFrame 会在我点击 / 时被渲染,然后反应路由器寻找 loginsign_up渲染其他容器.

然而,当我点击 / 时,只有 AuthFrame 会呈现.

我希望将 / 视为 /login.

我如何实现这一目标?

解决方案

Switch 组件在以下情况下很有用:

返回 (<AuthFrame footerText={footerText} footerClick={footerClick}><开关><Route path="/login" component={LoginContainer}/><Route path="/sign_up" component={SignUpContainer}/>{/* 默认路由,以防到目前为止 `Switch` 中没有匹配到 */}<路由组件={LoginContainer}/></开关></AuthFrame>);

参见:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md

I'm trying to do layouts with react-router.

When my user hits / I want to render some layout. When my user hits /login, or /sign_up I want the layout to render, with the relevant component for /login or /sign_up rendered.

Currently, my App.js looks like this

return (
  <div className={className}>
    <Route path="/" component={Auth} />
    <ModalContainer />
  </div>
);

My Auth.js looks like this

return (
  <AuthFrame footerText={footerText} footerClick={footerClick}>
    <Route path="/login" component={LoginContainer} />
    <Route path="/sign_up" component={SignUpContainer} />
  </AuthFrame>
);

So AuthFrame will get rendered when I hit /, and then react router looks for login or sign_up to render the other containers.

However, when I hit /, only the AuthFrame will render.

I would like for / to be treated as /login.

How do I achieve this?

解决方案

The Switch component is useful in these cases:

return (
  <AuthFrame footerText={footerText} footerClick={footerClick}>
    <Switch>
      <Route path="/login" component={LoginContainer} />
      <Route path="/sign_up" component={SignUpContainer} />
      {/* Default route in case none within `Switch` were matched so far */}
      <Route component={LoginContainer} />
    </Switch>
  </AuthFrame>
);

see: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md

这篇关于使用反应路由器布局路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆