React Router onEnter 错误
2016-09-18
412
我试图在 React Router 上将路由身份验证添加到我的 ReactJS 应用程序中,但是每当我将创建的身份验证函数添加到特定路由上的 on enter 属性时,我都会收到以下错误。
Uncaught RangeError:超出最大调用堆栈大小
我的路线
// 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个回答
要修复错误,您必须将
replace
代码从
replace({
path: '/login',
state: {next: nextState.location.pathname}
});
更改为
replace({
pathname: '/login',
state: {nextPathname: nextState.location.pathname}
});
Dhruv Kumar Jha
2016-09-19
尝试更改 localStorage.token 的返回方式。
const loggedIn = () => {
return localStorage.token;
}
Shubham Khatri
2016-09-19