检查用户是否已登录以在响应中使用Firebase [英] Check if user is logged in or not using firebase in react

查看:85
本文介绍了检查用户是否已登录以在响应中使用Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实有一个reactfirebase项目.因此,我能够通过firebase身份验证成功登录用户.我要做的是在所有页面中设置用户详细信息.我以为,我可以在任何地方访问用户变量,例如laravel的Auth::user().但是我尝试了很多方法来实现这一目标.但是我无法在另一页上获取用户详细信息.有什么方法可以在另一页上获取用户详细信息吗?

I do have a react with firebase project. So I successfully able to login the user via firebase authentication. What I want to do is to set the user details in all pages. I thought, I can able to access the user variables in react everywhere like laravel's Auth::user() . But I tried in so many ways to achieve that. But I couldn't able to get the user details in another page. Is there any way to get the user details in another page ?

我的signin.js页面.

  handleSubmit = (e) => {
    e.preventDefault()
    firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then((user) => {
      alert("login success")
      console.log(user.user)
      this.setState({uid:user.user.uid})
      localStorage.setItem('uid',JSON.stringify(user.user))
      window.location.assign('/')
      }).catch(function(error) {
            console.log(error.code)
            alert(error.message)
        })
      }

我的dashboard.js页面,我要在其中访问用户变量.

My dashboard.js page where I want to access user variables .

  componentDidMount() {
    if(localStorage.getItem('uid')){
      //alert("welcome"+localStorage.getItem('uid'));
      this.setState({user : JSON.parse(localStorage.getItem('uid'))})
      console.log("this : "+localStorage.getItem('uid'))
    }
  }

推荐答案

var user = firebase.auth().currentUser;
var name, email, photoUrl, uid, emailVerified;

if (user != null) {
  name = user.displayName;
  email = user.email;
  photoUrl = user.photoURL;
  emailVerified = user.emailVerified;
  uid = user.uid;  // The user's ID, unique to the Firebase project. Do NOT use
                   // this value to authenticate with your backend server, if
                   // you have one. Use User.getToken() instead.
}

您可以在firebase.auth()回调上使用currentUser方法来获取用户详细信息. 如果您使用前端Firebase程序包登录,则无论是在同一页面还是在其他任何页面上都可以调用

you can use currentUser method on firebase.auth() callback to fetch user details. If you are signing in using frontend firebase package then this is no issue, whether you call this on the same page or any other page

这篇关于检查用户是否已登录以在响应中使用Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆