【问题标题】:Redirect works even though it shouldn't render重定向工作,即使它不应该呈现
【发布时间】: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() &amp;&amp; &lt;Redirect to={routes.home}/&gt;},因为以前不是这样。还是一样
  • @Antonio 以及为什么顺便说一句,我认为最好阻止任何人进入 /auth 路线

标签: reactjs react-router-v4


【解决方案1】:

正如有人对我说的那样,通常您应该在注销后重新加载页面,如问题所述 - 重新加载后工作。

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2011-04-25
    • 1970-01-01
    • 2013-07-29
    • 2018-01-09
    相关资源
    最近更新 更多