首页 > 解决方案 > Reactjs路由器onEnter钩子认证导致无限循环

问题描述

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

这是我的代码:

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-router,onEnter 导致带有身份验证的无限循环

我都试过了,但不幸的是,这些例子对我没有帮助。(我也是 React 的初学者)

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

标签: reactjsauthenticationreact-routerinfinite-loop

解决方案


你会得到一个无限循环,因为如果用户登录它总是将他重定向到/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>
  )
}

我认为您将不得不在 hook 中使用回调


推荐阅读