我正在尝试在信息中心页面上重定向登录用户。
这是我的代码:
function requireAuth(nextState, replace) {
if(isLoggedIn()) {
console.log("user is logged in");
replace('/dashboard');
} else {
replace('/');
}
}
const Root = () => {
return (
<div className="container">
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route onEnter={requireAuth}>
<Route path="dashboard" component={AllEvents}/>
</Route>
</Route>
</Router>
</div>
)
}
当用户登录时,我的应用程序将使用requireAuth
方法进入循环。
我已经在StackOverflow上考虑过两个类似的问题:
react Maximum call stack size exceeded
React-router, onEnter cause infinite loop with authentication
我试过了他们两个,但不幸的是,这些例子对我没有帮助。 (我也是React的初学者)
请告诉我我的代码有什么问题?
答案 0 :(得分:2)
你得到一个无限循环,因为如果用户被记录,它总是将他重定向到/dashboard
并从/
开始重复重定向过程并再次点击requireAuth
。
尝试:
function onlyUnAuthenticated(nextState, replace, callback) {
if(isLoggedIn()) {
replace('/dashboard');
}
callback();
}
function onlyAuthenticated(nextState, replace, callback) {
if(!isLoggedIn()) {
replace('/');
}
callback();
}
const Root = () => {
return (
<div className="container">
<Router history={browserHistory}>
<Route path="/" component={App} onEnter={onlyUnAuthenticated}>
<Route path="dashboard" component={AllEvents} onEnter={onlyAuthenticated}/>
</Route>
</Router>
</div>
)
}
我认为您必须use callback in the hook。