2016-09-18 77 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; 
}