Reactjs router onEnter 挂钩认证导致无限循环
Reactjs router onEnter hook authentication cause infinite loop
我正在尝试重定向仪表板页面上的登录用户。
这是我的代码:
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
方法的循环。
这是控制台的屏幕截图。
我已经在 Whosebug 上考虑过两个类似的问题,它们是:
我都试过了,但不幸的是,这些例子对我没有帮助。 (我也是 React 的初学者)
请告诉我我的代码有什么问题?
你得到一个无限循环,因为如果用户登录,它总是将他重定向到 /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。
我正在尝试重定向仪表板页面上的登录用户。
这是我的代码:
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
方法的循环。
这是控制台的屏幕截图。
我已经在 Whosebug 上考虑过两个类似的问题,它们是:
我都试过了,但不幸的是,这些例子对我没有帮助。 (我也是 React 的初学者)
请告诉我我的代码有什么问题?
你得到一个无限循环,因为如果用户登录,它总是将他重定向到 /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。