reactjs - Reactjs路由器onEnter钩子认证导致无限循环
问题描述
我正在尝试在仪表板页面上重定向登录用户。
这是我的代码:
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-router,onEnter 导致带有身份验证的无限循环
我都试过了,但不幸的是,这些例子对我没有帮助。(我也是 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>
)
}
我认为您将不得不在 hook 中使用回调。
推荐阅读
- jquery - 如何在 laravel 的 jquery 中调用 ajax
- laravel - 批量更新多列时出错
- c++ - 使用指针将第一个(2D)数组的值复制到第二个的函数
- elasticsearch - simple_query_string 检查字段是否存在
- python - Python 全局变量名在函数内部被本地处理
- docker - 无法在 jenkins docker 映像中添加 jenkins-job-builder
- javascript - 抓取动态站点(PhantomJS)的问题
- python - 具有多个参数的 Python SQL SELECT 语法 LIMIT
- python - 给定每个组的起始位置索引时的 Groupby
- mysql - 列出与 MySQL 在同一个表中具有相同 ID 的行