gpt4 book ai didi

javascript - react 路由器 onEnter 错误

转载 作者:行者123 更新时间:2023-11-29 14:40:04 25 4
gpt4 key购买 nike

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

未捕获的 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;

最佳答案

要修复错误,您必须更改您的replace 代码

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

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

关于javascript - react 路由器 onEnter 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39559329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com