使用react-router-dom在子组件中进行路由

时间:2018-09-03 08:49:31

标签: reactjs react-router-dom core-ui

我正在将CoreUI Pro模板用于React仪表板,并尝试将登录功能集成到其中。我的登录使用的是AWS Cognito,因此该部分使用了this教程。

我的问题是,登录后,链接不起作用。

我的顶级route.js在下面。

export default ({ childProps }) =>
  <HashRouter>
    <Switch>
      <AppliedRoute path='/' exact component={Login} props={childProps} />
      <UnauthenticatedRoute path='/login' exact component={Login} props={childProps} />
      <AuthenticatedRoute path='/dashboard' exact component={Full} props={childProps} />
      <Route component={NotFound} />
    </Switch>
  </HashRouter>

在登录组件中,我重定向到/ dashboard,并且可以正常工作。完整是包含仪表板的组件的名称。

一旦用户位于“完整”组件中,那么我希望他们能够浏览:

<Container fluid>
              <Switch>
                <Route path='/dashboard' name='Dashboard' component={Dashboard} />
                <Route path='/deliveries/listDeliveries' name='List Deliveries' component={ListDeliveries} />
                <Route path='/shifts/listShifts' name='List Shifts' component={ListShifts} />
                <Route path='/locations/' name='Locations' component={Locations} />
                <Redirect from='/' to='/dashboard' />
              </Switch>
            </Container>

这在CoreUI模板中有效,但是对我来说,如果我登录后导航到/ locations,它将转到我的404页面。我考虑过将所有内容都移到route.js,但问题是Full的页面周围有一个模板,它只是在页面的一个区域中加载了Locations之类的组件。

1 个答案:

答案 0 :(得分:0)

您正在嵌套路线-请参见参考示例here

问题是,到Full组件的路径中具有 exact 属性,因此在浏览到/locations路径时该组件将不会呈现。我建议重新组织您的路线,以便您可以像上面的示例一样构建它(例如/dashboard/deliveries)。

然后,您将在顶级路由中保留 exact 属性,并在Full组件中包含以下路由:

<Route 
  path={this.props.match.url + '/deliveries/listDeliveries'}
  name='List Deliveries'
  component={ListDeliveries}
/>

这将与路由/dashboard/deliveries/listDeliveries相匹配。