检查用户是否已登录或未在 React 中使用 Firebase

far*_*ooq 5 laravel firebase reactjs firebase-authentication

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

我的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)
        })
      }
Run Code Online (Sandbox Code Playgroud)

dashboard.js想要访问用户变量的页面。

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

Kev*_*RED 5

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.
}
Run Code Online (Sandbox Code Playgroud)

您可以使用回调currentUser方法firebase.auth()来获取用户详细信息。如果您使用前端 firebase 包登录,那么无论您在同一页面还是任何其他页面上调用它都没有问题

  • onAuthStateChanged 用于检查身份验证状态是否更改。它似乎不会向您提供用户详细信息。如果您想要用户详细信息并调用我提到的方法,您可以在页面上导入 firebase (并且仅是 firebase) (2认同)