我有如下所示的路由,如果有人单击主页上的 ADMIN 按钮(此按钮路由到/admin),我想将用户重定向到管理/用户页面,但我收到此错误:
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 中添加了位置属性,因为我在路由时使用动画。您可以在此链接中找到示例:https://reacttraining.com/react-router/web/example/animated-transitions
- 如果我删除位置属性,一切都很好,但使用此属性时,我会收到错误。
- 我搜索了很多网站并尝试了一些方法,但我无法实现。我需要位置属性,但无法删除它。
如果您能帮助我,我将不胜感激。
谢谢
最佳答案
只有编写以下代码才能实现:
<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 不阻止?有人能回答这个问题吗?
关于reactjs - React 路由器给出 "redirect to the same route"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50984242/