首页 > 解决方案 > How to make redirect in nested routes with React Router

问题描述

After signin process my app redirects to /admin/dashboard , and when entering dashboard path i want my app to load first component and redirect to /admin/dashboard/profiles. In App.js component i have code

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

In component i have code

    <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>

It only loads component when the path of first component is path={${match.url}/} , but when path is /admin/dashboard/profiles it does not render Profiles component. What am i doing wrong ?

标签: reactjsreact-router

解决方案


You are using an exact attribute on the top level route

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

Which is why any nested route won't match. Remvove the exact attribute from the parent route and it would work for you

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

Also for paths, you must use match.path instead of match.url. match.url should be used for Link and Redirect component


推荐阅读