2016-09-18 93 views
3

我试图将路由验证添加到我的reactjs应用程序上的反应路由器,但每当我添加身份验证功能创建到上特定路线上输入属性我收到以下错误。反应路由器onEnter错误

Uncaught RangeError: Maximum call stack size exceeded

我的路线

// libraries 
import React from '../node_modules/react'; 
import {Router, Route, browserHistory, IndexRoute, Redirect} from '../node_modules/react-router'; 
// route middleware 
import requiresAuth from '../middleware/requiresAuth'; 
// components 
import App from '../modules/other/app.jsx'; 
import Dashboard from '../modules/stats/dashboard.jsx'; 
import Login from '../modules/auth/login.jsx'; 
import NotFound from '../modules/errors/notfound.jsx'; 
// routes 
export const routes = 
    <Router history={browserHistory}> 
     <Route path="/" component={App}> 
      <IndexRoute component={Dashboard} onEnter={requiresAuth} /> 
      <Route path="dashboard" name="dashboard" component={Dashboard} onEnter={requiresAuth} /> 
      <Route path="login" name="login" component={Login} /> 
      <Route path="*" name="notfound" component={NotFound} /> 
     </Route> 
    </Router>; 

我的认证功能

const requiresAuth = (nextState, replace) => { 
    if (!loggedIn()) { 
     replace({ 
      path: '/login', 
      state: {next: nextState.location.pathname} 
     }); 
    } 
} 

const loggedIn =() => { 
    return !!localStorage.token; 
} 

export default requiresAuth; 
+0

你可以上传你的整个应用程序/文件航线代码? –

+0

@RandomUser我刚刚做了 –

+2

首先,当你导入一个你用npm安装的模块时,你可以直接使用它的名字,而不是在导入它时提供相对路径,所以改变'import React from'。 ./node_modules/react';'为'从'react'中导入React;'并且为'react-router'做同样的事情 –

回答

1

要修正这个错误,你必须从

replace({ 
    path: '/login', 
    state: {next: nextState.location.pathname} 
}); 

更改replace代码要

replace({ 
    pathname: '/login', 
    state: {nextPathname: nextState.location.pathname} 
}); 
1

尝试并做出改变如何返回localStorage.token。

const loggedIn =() => { 
    return localStorage.token; 
}