【问题标题】:How to make redirect in nested routes with React Router如何使用 React Router 在嵌套路由中进行重定向
【发布时间】:2020-05-02 18:27:47
【问题描述】:

在登录过程之后,我的应用程序重定向到 /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 组件。我做错了什么?

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    你在顶级路由上使用了一个确切的属性

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 2020-09-22
      • 2016-05-02
      • 1970-01-01
      • 2017-07-04
      • 2016-03-06
      • 2017-11-11
      相关资源
      最近更新 更多