【发布时间】:2019-08-12 11:53:10
【问题描述】:
我正在为我的 react 应用程序进行授权,如果用户已登录,我已经从 /auth 路由进行了重定向。注销后,重定向仍然有效,即使 Api 中的 isLoggedIn 值已更改确定(与console.log确认)
我也不知道为什么,所以我只是尝试改变一些Api方法,isLoggedIn之前是一个对象的get属性,现在它是函数。
function Auth(){
return (
<div>
<Header theme="light"/>
<Switch>
{Api.Auth.isLoggedIn() && <Redirect to={routes.home}/>}
<Route path={routes.login} component={Login}/>
<Route path={routes.register} component={Register}/>
</Switch>
</div>
);
}
API:
isLoggedIn() {
console.log(this._token, !!this._token); // test, returns false everytime, but redirect works...
return !!this._token;
},
logout(){
this._token = null;
this._axiosSetToken('');
try {
window.localStorage.removeItem('token');
} catch (e) {
console.error(e);
}
}
我还有一件事正在使用相同的登录检查(在标题中显示或现在带有头像的个人资料链接,但它工作正常并出现登录按钮。
F5(页面重新加载)后一切正常,我在注销之前或之后重新加载页面都没关系 - 它会起作用。
【问题讨论】:
-
你能为此创建一个codepen吗?你应该把你的重定向移出开关。
-
如何确保您的 Auth 组件重新呈现,从而在调用
API.Auth.logout后重新验证用户isLoggedIn?你目前使用的是 Mobx、Redux 还是 React Context?听起来您正在使用按钮组件这样做。 -
@Khauri 我正在使用 Redux 登录,但注销基本上是清理令牌并重定向到主页。并且条件基于令牌,所以它应该可以工作......
-
@Antonio @Domino987 我已经将重定向移出 Switch(它是
{Api.Auth.isLoggedIn() && <Redirect to={routes.home}/>},因为以前不是这样。还是一样 -
@Antonio 以及为什么顺便说一句,我认为最好阻止任何人进入 /auth 路线