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

标签 reactjs react-router-v4 react-router-dom

我有如下所示的路由,如果有人单击主页上的 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/

相关文章:

javascript - 如何测试带有 <Router> 标签的组件?

javascript - 显示旧数据的 Reactjs 组件

node.js - Loadable.Capture 不报告任何模块

javascript - history.listen 未在 componentDidMount 中触发

javascript - react 路由器页面无法刷新

javascript - 应该如何在 React 类中编写函数?

reactjs - React 组件重新执行错误

javascript - React 路由器呈现空白页面

javascript - 如何从使用react-router匹配的 <Route/> 组件之外的组件检测匹配的路由?

reactjs - 从react-router-dom url中删除哈希