在 React.JS 中刷新后,如何让用户保持登录到 firebase?
Posted
技术标签:
【中文标题】在 React.JS 中刷新后,如何让用户保持登录到 firebase?【英文标题】:How do I keep a user logged into firebase after refresh in React.JS? 【发布时间】:2018-07-29 01:54:08 【问题描述】:安装组件时,我想渲染登录屏幕或应用程序,具体取决于用户是否登录。但是,每次刷新时,用户都会注销。我如何让他们保持登录状态?
应用组件:
firebase.initializeApp(config); //init the firebase app...
class App extends Component //this component renders when the page loads
constructor(props)
super(props);
this.state = user: firebase.auth().currentUser;//current user
render()
if (this.state.user) //if you are logged in
return (
<Application/>
);
else //if you are not logged in
return (
<Authentication/>
);
这是我用来登录用户的方法(效果很好):
let email = "some";
let password = "thing";
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, password);
【问题讨论】:
【参考方案1】:用户的令牌会自动持久化到本地存储,并在页面加载时读取。这意味着当您重新加载页面时,应该自动再次对用户进行身份验证。
最可能的问题是您的代码未检测到此身份验证,因为您的 App
构造函数在 Firebase 重新加载并验证用户凭据之前运行。要解决此问题,您需要 listen for the (asynchronous) onAuthStateChanged()
event,而不是同步获取值。
constructor(props)
super(props);
firebase.auth().onAuthStateChanged(function(user)
this.setState( user: user );
);
【讨论】:
您还可以获得一些您可能想要配置的身份验证状态持久性选项firebase.google.com/docs/auth/web/auth-state-persistence 用户令牌如何保存在本地存储中?我想对订阅用户做类似的事情。【参考方案2】:我在 React 中遇到了与 Firebase 相同的问题。尽管 Firebase 具有内部持久性机制,但您在重新加载浏览器页面时可能会遇到闪烁/故障,因为您接收经过身份验证的用户的 onAuthStateChanged
侦听器需要几秒钟的时间。这就是我使用本地存储在 onAuthStateChanged 监听器中设置/重置它的原因。类似于以下内容:
firebase.auth.onAuthStateChanged(authUser =>
authUser
? localStorage.setItem('authUser', JSON.stringify(authUser))
: localStorage.removeItem('authUser')
);
那么就可以在应用启动时在一个React组件的构造函数中取回:
constructor(props)
super(props);
this.state =
authUser: JSON.parse(localStorage.getItem('authUser')),
;
您可以通过here了解更多信息。
【讨论】:
这个答案很好 把用户信息存入localStorage可以吗? @Robin,我已经尝试了这里的建议,仍然有问题,在这里发布了一个非常相似的问题(***.com/q/64024613/2534233),我可能做错了什么? 如果用户离开网站并且令牌过期会怎样?当他们重新访问时,由于 localStorage 仍然包含用户信息,所以不会有一个经过身份验证的数据闪现吗?【参考方案3】:个人觉得这种方式最好,也最简单。
state = authUser: null,show:'none';
componentDidMount()
firebase.auth().onAuthStateChanged(user =>
if (user) this.setState( authUser: true,show:'block')
else this.setState( authUser: false,show:'none')
)
return /*important*/ this.state.authuser==false?
<Login/>
:this.state.authuser==true?
<Home style=display:this.state.show/>
:<div>/*show loading/spash page*/
</div>
您还可以使用 Home 作为默认路由添加路由('/' 不要使用确切路径,使用路径代替),然后如果用户自动重新路由到登录或注册没有登录。
【讨论】:
通常当有人重新加载页面时,他们会瞥见您的页面(在它重新路由到“登录”之前,至少在我开发时似乎......),因此有能力拥有一个启动页面设置对用户来说非常好,而不是看到一个闪烁的页面......据说可能有更好的方法来做这些事情,但对于 MVP 来说它是完美的,因此是最好的和最简单的方法:) @Greg以上是关于在 React.JS 中刷新后,如何让用户保持登录到 firebase?的主要内容,如果未能解决你的问题,请参考以下文章