【问题标题】:useEffect() and Google Firebase onAuthStateChangeuseEffect() 和 Google Firebase onAuthStateChange
【发布时间】:2021-08-09 22:41:54
【问题描述】:

每当组件挂载时,都会调用 onAuthStateChange(setCurrentUser),其中传入了一个设置 currentUser 状态的函数。Firebase 然后根据用户是否登录返回一个身份验证对象,我用它来设置currentUser 的状态以及使用 createUserDocument() 将数据保存在 firestore 中。

auth.onAuthStateChanged(async userAuth ....) 返回什么?我很困惑,因为它的返回值被分配给取消订阅,每当组件卸载时都会调用它。

function onAuthStateChange(callback) {
  return auth.onAuthStateChanged(async userAuth => {
    if (userAuth) {
      const userRef = await createUserDocument(userAuth); 
      userRef.onSnapshot(snapShot => {
        callback({
          id: snapShot.id, 
          ...snapShot.data()
        })
      })
    } else {
      callback(null); 
    }
  })
}

function App() {
  const [currentUser, setCurrentUser] = useState(null); 
  useEffect(() => {
      const unsubscribe = onAuthStateChange(setCurrentUser); 
      return () => {
        unsubscribe(); 
      }; 
  }, [])

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore firebase-authentication react-hooks


    【解决方案1】:

    根据documentation onAuthStateChanged 返回firebase.Unsubscribe。当您调用此函数时,Firebase 会确保从 Observables 中删除此请求(因此 firebase 不会通知您不再存在的组件,这可以防止错误或内存泄漏或浪费计算能力)。

    Observables 是在 Firebase 内部实现的,这就是当特定状态发生变化时它们决定谁请求通知的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-29
      • 2020-03-23
      • 1970-01-01
      • 2018-08-10
      • 2019-08-17
      • 2019-10-24
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多