在重新加载单页反应应用程序时保持谷歌登录持久



我目前正在制作一个react-redux应用程序,它使用Google登录来验证用户。

该应用程序使用反应谷歌登录实现如下:

render() {
return (
<div>
<h2>   Find destinations ✈️</h2>
<GoogleLogin
clientId={this.googleClientId}
buttonText="Sign-in with Google"
onSuccess={this.responseGoogle}
/>
</div>
);
}

目前,如果我运行此代码,在单击登录按钮时,我能够访问登录令牌和其他用户信息,从而允许登录,但是如果我重新加载页面,这将丢失,因为应用程序将恢复到原始状态。

如何在重新加载后使用 OAuth2 保持 Google 登录的持久性?

我最终使用了可用作window对象的localStorage。从Google OAuth检索用户信息后,我将电子邮件、姓名等相关部分保存在localStorage中;具体操作如下:

在本地存储中设置键 (例如在 onLogin())中:

localStorage.setItem('userInfo', JSON.stringify(loginResponse));

从 localStorage(例如 inside constructor())获取键值

var user = JSON.parse(localStorage.getItem('userInfo'));

清除本地存储(例如,在 onLogout()) 中:

localStorage.clear();

最新更新