首页 文章

React Router 4 - 定义没有路径的布局路径

提问于
浏览
3

我正面临着试图定义无路径布局路径的问题(这在路由器3中是可能的) . 基本上我想要实现的是:在我的index.js中:

<Router history={history}>
        <Route path="/" component={App}/>
    </Router>

在我的App组件中定义布局

<Switch>
    <Route path="" component={AuthLayout}/>
    <Route path="" component={MainLayout}/>
</Switch>

现在因为它们只是布局,我希望它们执行一些功能并定义它们的嵌套路由,例如

在AuthLayout中:

<Switch>
     <Route exact path={`${match.path}/sign-up`} component={SignUpContainer}/>
     <Route exact path={`${match.path}/login`} component={LoginContainer}/>
                                <Route component={SignUpContainer}/>
</Switch>

并在MainLayout中:

<Switch>
      <Route exact path={`${match.path}/explorer`} component={ExplorerContainer}/>
//more routes 
      <Route component={NotFoundContainer}/>
    </Switch>

现在我知道它不会工作,因为switch总是会触及第一个项目,如果没有Switch,它将呈现两个组件 . 我想要实现的是一个浅网址,所以我不想为布局定义路由 . 在RRTR 3中有可能,但我无法弄清楚我是否可以在RRTR 4中做到这一点

仅供3参考,我这样做:

<Route path="/" component={App}>
            <IndexRedirect to="login"/>
            /*Profile Management Flows*/
            <Route path="" component={AuthLayout}>
                <Route path="login" component={LoginContainer}/>
                <Route path="sign-up" component={SignUpContainer}/>
                <Route path="forgot-password" component={ForgotPasswordContainer}/>
                <Route path="reset-password" component={ResetPasswordContainer}/>
                <Route path="on-boarding" component={OnBoardingContainer}/>


            </Route>

任何建议?我应该放弃并为每个布局添加路径吗?我应该坚持RRTR3吗?

2 回答

  • 0

    是的,你将无法完全按照你对React Router 3所做的那样 . 我认为可以通过以下方式实现类似的功能:

    <Switch>
      <Route path="/(login|signup|forgot-password|reset-password)" render={({ location }) => (
        <AuthLayout>
            <Switch>
              <Route path="/login" component={/* ... */} />
              <Route path="/signup" component={/* ... */} />
              {/* ... */}
            </Switch>
        </AuthLayout>
      )} />
      <Route path="/" component={MainLayout} />
    </Switch>
    
  • 0

    我建议将所有路由放在一个开关中,并指定在每个容器中使用的布局 . 它将更容易维护 .

    <Switch>
         <Route path="/sign-up" component={SignUpContainer}/>
         <Route path="/login" component={LoginContainer}/>
         <Route path="/explorer" component={ExplorerContainer}/>
         <Route path="/" component={MainLayout} />
    </Switch>
    

    如果您想保护路由免受未经授权的用户的攻击,您可以使用 Higher order component . 我解释了如何在这里实现:React router v4 - Authorized routes and components

    我发现以下关于React Router 4的文章非常有用:https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf

相关问题