【问题标题】:Reactjs router onEnter hook authentication cause infinite loopReactjs路由器onEnter钩子认证导致无限循环
【发布时间】:2018-10-16 05:11:56
【问题描述】:

我正在尝试在仪表板页面上重定向登录用户。

这是我的代码:

function requireAuth(nextState, replace) {
  if(isLoggedIn()) {
    console.log("user is logged in");
    replace('/dashboard');
  } else {
    replace('/');
  } 
}

const Root = () => {
  return (
    <div className="container">
      <Router history={browserHistory}>
        <Route path="/" component={App}>
          <Route onEnter={requireAuth}>
            <Route path="dashboard" component={AllEvents}/>
          </Route>
        </Route>
      </Router>
    </div>
  )
}

当用户登录时,我的应用程序正在使用requireAuth 方法运行到一个循环中。

这是控制台的屏幕截图。

我已经在 StackOverflow 上考虑过两个类似的问题,它们是:

react Maximum call stack size exceeded

React-router, onEnter cause infinite loop with authentication

我已经尝试了这两种方法,但不幸的是,这些示例对我没有帮助。 (我也是 React 的初学者)

请告诉我我的代码有什么问题?

【问题讨论】:

  • 你使用哪个版本的 react-router?
  • @MotiKorets 我对我的版本很困惑,因为在 packaje.json 我有 "react-router": "^3.2.1" ,但是在执行 "npm react-router -- v" 我得到了 5.8.0
  • 运行 npm show react-router version 以查看软件包版本。你运行的内容显示npm 版本。无论如何我猜它是 react-router 3
  • @MotiKorets npm show react-router version 显示 4.2.0
  • 你试过&lt;Route path='dashboard' onEnter={requireAuth}&gt;而不是像你一样嵌套仪表板路由吗?

标签: reactjs authentication react-router infinite-loop


【解决方案1】:

你会得到一个无限循环,因为如果用户登录它总是将他重定向到/dashboard,并从/开始重复重定向过程,然后再次点击requireAuth

试试:

function onlyUnAuthenticated(nextState, replace, callback) {
  if(isLoggedIn()) {
    replace('/dashboard');
  }
  callback();
}

function onlyAuthenticated(nextState, replace, callback) {
  if(!isLoggedIn()) {
    replace('/');
  } 
  callback();
}

const Root = () => {
  return (
    <div className="container">
      <Router history={browserHistory}>
        <Route path="/" component={App} onEnter={onlyUnAuthenticated}>
          <Route path="dashboard" component={AllEvents} onEnter={onlyAuthenticated}/>
        </Route>
      </Router>
    </div>
  )
}

我认为你必须use callback in the hook

【讨论】:

    猜你喜欢
    • 2021-04-10
    • 2020-03-25
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 2020-12-14
    相关资源
    最近更新 更多