【问题标题】:Routing in child component using react-router-dom使用 react-router-dom 在子组件中路由
【发布时间】:2018-09-03 08:49:30
【问题描述】:

我正在为 React 仪表板使用 CoreUI Pro 模板,并尝试将登录功能集成到其中。我的登录是使用 AWS Cognito,所以我使用 this 教程来完成这部分。

我的问题是登录后链接失效了。

我的顶级 routes.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 并且工作正常。 Full 是包含仪表板的组件的名称。

一旦用户在 Full 组件中,我希望他们能够四处导航:

<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 页面。我曾考虑将所有内容都移至 routes.js,但问题是 Full 有一个围绕页面的模板,它只是在页面的一个区域加载诸如 Locations 之类的组件。

【问题讨论】:

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


    【解决方案1】:

    您正在嵌套路由 - 请参阅示例以供参考 here

    问题是,您在到 Full 组件的路由中具有 exact 属性,因此在浏览到 /locations 路由时组件不会呈现。我建议重组你的路线,这样你就可以像上面的例子那样组织它(例如/dashboard/deliveries)。

    然后,您将在顶级路由中省略 exact 属性,并在您的 Full 组件中拥有这样的路由:

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

    这将匹配路由/dashboard/deliveries/listDeliveries

    【讨论】:

    • 谢谢,已解决
    猜你喜欢
    • 1970-01-01
    • 2018-01-28
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 2022-07-09
    • 2021-02-07
    • 2017-10-12
    • 2021-11-11
    相关资源
    最近更新 更多