【问题标题】:getAuth() return a object but uid return null when page reloadgetAuth() 返回一个对象,但页面重新加载时 uid 返回 null
【发布时间】:2021-12-13 14:17:30
【问题描述】:

我的代码太庞大了;我只是放了一部分我认为必不可少的代码。

import {getAuth} from "firebase/auth"

const authFirebase = getAuth()
console.log(authFirebase)

const Home = () => {
  ...
  return(
   ...
  )
}

每当我重新加载页面 (F5) 时。

console.log(authFirebase)

我在 currentUser 属性中检索到一个包含 uid 的对象,但是当我这样编码时。

 console.log(authFirebase.currentUser.uid)

我收到了这个错误

TypeError: Cannot read properties of null (reading 'uid')

我很困惑;我对 Firebase 不了解?

【问题讨论】:

    标签: javascript firebase firebase-authentication


    【解决方案1】:
    import { getAuth, onAuthStateChanged } from "firebase/auth";
    
    const auth = getAuth();
    onAuthStateChanged(auth, (user) => {
      if (user) {
        // User is signed in, see docs for a list of available properties
        // https://firebase.google.com/docs/reference/js/firebase.User
        const uid = user.uid;
        // ...
      } else {
        // User is signed out
        // ...
      }
    });
    

    【讨论】:

      【解决方案2】:

      原因是您在该对象准备好使用之前获取用户对象。

      如果存在,您需要将其包装在一个条件中,然后登录到控制台。

      另一种方法是添加一个像 onAuthStateChanged 这样的观察者,这将解决预取对象的问题。

      firebase.auth().onAuthStateChanged( user =>; {
        if (user) { console.log(user) }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-07
        • 1970-01-01
        • 1970-01-01
        • 2021-08-18
        • 2012-05-19
        • 1970-01-01
        • 2012-07-25
        相关资源
        最近更新 更多