如何以正确的方式在React Router v4中使用Redirect?

时间:2017-05-04 20:09:36

标签: react-router-v4

我有这样的路线:

<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/*路由重定向到/dashboard/my-account

如何使用类似于prev中的功能的React Router v4。版本

感谢。

2 个答案:

答案 0 :(得分:0)

我也遇到了这种情况。以下是我对<Switch>所做的事情:

<Switch>
  <Route exact path="/dashboard" render={() => <Redirect to="dashboard/my-account" />} />
  <Route path="/dashboard/my-account" />
  <Route path="/dashboard/service-request" />
  <Route path="/dashboard/payments" />
  <Route path="/dashboard/settings" />
</Switch>

有了这个。 /dashboard会重定向到/dashboard/my-account,但/dashboard/foo不会匹配任何内容。我建议添加一个NotFound组件或其他东西来捕获404。

答案 1 :(得分:0)

因此,仍然有问题的任何人都可以像这样在重定向组件上使用严格的布尔值:

<Switch>
  <Redirect strict 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>

这将确保只有 /dashboard 被重定向到 /dashboard/my-account