繁体   English   中英

如何使用 React Router 在嵌套路由中进行重定向

[英]How to make redirect in nested routes with React Router

登录过程后,我的应用程序重定向到 /admin/dashboard,当输入仪表板路径时,我希望我的应用程序加载第一个组件并重定向到 /admin/dashboard/profiles。 在 App.js 组件中,我有代码

<Router>
    <Layout>
      <Navbar />
      <Switch>
        ...
        <Route exact path="/admin/dashboard" component={Dashboard}/>
        ...
      </Switch>
    </Layout>
  </Router>

在组件中我有代码

    <Layout>
      <Sidebar />
      <Switch>
        <PrivateRoute path={`${match.url}/profiles`} component={Profiles} />
        <PrivateRoute path={`${match.url}/tests`} component={Tests} />
        <PrivateRoute path={`${match.url}/settings`} component={Settings} />
      </Switch>
    </Layout>

它仅在第一个组件的路径为 path={ ${match.url}/ } 时加载组件,但当路径为 /admin/dashboard/profiles 时,它不会呈现 Profiles 组件。 我究竟做错了什么?

您正在顶级路线上使用确切的属性

<Route exact path="/admin/dashboard" component={Dashboard}/>

这就是为什么任何嵌套路由都不匹配的原因。 从父路由中删除确切的属性,它会为你工作

<Route path="/admin/dashboard" component={Dashboard}/>

同样对于路径,您必须使用match.path而不是match.url match.url应该用于LinkRedirect组件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM