【问题标题】:Firebase auth onAuthChange proper way to useFirebase auth onAuthChange 正确使用方法
【发布时间】:2021-01-31 17:18:19
【问题描述】:

我正在尝试使用 firebase auth 模块,但是当我尝试使其与取消订阅的方法一起使用时,它不会调用该方法本身。我的第一个方法是没有取消订阅方法,虽然有效但可能让我有内存泄漏:

useEffect(() => {
    firebase.auth().onAuthStateChanged((user) => {
      // My method
    });
  }, []);

然后我一直在检查一些网站和 stackoverflow 问题,他们说应该这样做:

useEffect(() => {
    const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
      // My method
    });

    return unsubscribe();
  }, []);

这只是不调用 firebase.auth().onAuthChanged 方法。有什么建议吗?

非常感谢。

【问题讨论】:

    标签: javascript reactjs firebase-authentication


    【解决方案1】:

    您的第二个示例实际上是调用返回的取消订阅函数,然后返回该调用的结果(不返回任何内容)。那是不对的。您只想在不再需要观察者时返回取消订阅函数本身,以便react can call it later

    useEffect(() => {
        const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
          // My method
        });
    
        // Just return the unsubscribe function.  React will call it when it's
        // no longer needed.
        return unsubscribe;
      }, []);
    

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 1970-01-01
      • 2020-01-20
      • 2018-03-02
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      相关资源
      最近更新 更多