React Router onEnter Error

时间:2016-09-18 15:26:01

标签: javascript reactjs react-router

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

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;

2 个答案:

答案 0 :(得分:1)

尝试更改localStorage.token的返回方式。

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

答案 1 :(得分:1)

要修正错误,您必须从

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

replace({
  pathname: '/login',
  state: {nextPathname: nextState.location.pathname}
});
相关问题