React 路由器给出 "redirect to the same route" 错误

React router gives "redirect to the same route" error

我有如下路由,如果有人单击主页上的 ADMIN 按钮(此按钮路由到 /admin),我想将用户重定向到 admin/users 页面,但我收到此错误:

You tried to redirect to the same route you're currently on: /admin/users

<Switch location={this.props.location}>
     <Route path="/" exact component={Home} />
     <Route path="/orders" component={Orders} />
     <Route path="/account" component={Account} />

     <Route path="/admin/users" component={Users} />
     <Route path="/admin/auth" component={Auth} />

     <Redirect from="/admin" to="/admin/users" />

     <Redirect from="*" to="/" />
</Switch>

如有帮助,我将不胜感激。

谢谢

不是解决方案,但会消除错误。

<Switch location={this.props.location}>
 <Route path="/" exact component={Home} />
 <Route path="/orders" component={Orders} />
 <Route path="/account" component={Account} />

 <Route path="/admin/users" component={Users} />
 <Route path="/admin/auth" component={Auth} />

 {allowedToRedirect
  ?(
    <Redirect from="/admin" to="/admin/users" />

    <Redirect from="*" to="/" />
   )
  : null}
</Switch>

哪里const allowedToRedirect = location.pathname === window.location.pathname; https://codesandbox.io/s/pjk4ykr4kq

只有写下面的代码才能实现:

<Route exact strict path="/admin" render={({location}) => {
    if (location.pathname === window.location.pathname) {
         return <Redirect to="/admin/users" />;
    }
    return null;
}} />

但是为什么Switch一次又一次地阻止到运行下面的重定向路由呢?因为当重定向发生时, /admin/users 路由有效,但 /admin 路由也有效。为什么Switch不阻止?有人对此有答案吗?