@IvanKalinin

Как правильно использовать Redirect в React Router 4 с вложенными роутами?

Всем доброго времени.
Помогите пожалуйста разобраться с react-router 4. А имеено редиректом.

Имеется такая структура роутов:

<Router history={this.props.history}>
  <div>
    <Route exact path="/" name="Home" component={Index} />
    <Route path="/colors" component={Palette} />
    <Route path="/icons" component={Icons} />
    <Route path="/forms" component={Forms} />
    <Route path="/other" component={Other} />
    <Route path="/dashboard" component={Dashboard} />
    <Switch>
      <Redirect from="/dashboard" to="/dashboard/my-account" />
      <Route exact path="/dashboard/my-account" />
      <Route exact path="/dashboard/service-request" />
      <Route exact path="/dashboard/payments" />
      <Route exact path="/dashboard/settings" />
    </Switch>
  </div>
</Router>


Идея в том, что при переходит на роут `dashboard` приложение должно делать редирект на первый "вложенный" роут т.е. на `/dashboard/my-account`. Но при данной структуре при открытии любого другого вложенного роута, например, `/dashboard/settings` происходит редирект на `/dashboard/my-account`.

Как правильно использовать перенаправление?
  • Вопрос задан
  • 2176 просмотров
Решения вопроса 1
@IvanKalinin Автор вопроса
Решил вопрос след. образом:
App.js
<Router history={this.props.history}>
  <Switch>
    <Route exact path="/" name="Home" component={Index} />
    <Route path="/colors" component={Palette} />
    <Route path="/icons" component={Icons} />
    <Route path="/forms" component={Forms} />
    <Route path="/other" component={Other} />
    <Route strict path="/dashboard" component={Dashboard} />
  </Switch>
</Router>


Dashboard.js
render() {
  return (
    <div className="DashboardComponent">
     // ...
      <Switch>  
        <Route exact path="/dashboard/my-account" component={MyAccount} />
        <Route exact path="/dashboard/service-request" component={ServiceRequest} />
        <Route exact path="/dashboard/payments" component={Payments} />
        <Route exact path="/dashboard/settings" component={Settings} />
        <Redirect to="/dashboard/my-account" />
      </Switch>
    </div>
  )
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы