簡體   English   中英

Firebase auth onAuthChange 正確使用方法

[英]Firebase auth onAuthChange proper way to use

我正在嘗試使用 firebase 身份驗證模塊,但是當我嘗試使其與取消訂閱的方法一起使用時,它不會調用該方法本身。 我的第一個方法是沒有取消訂閱方法,但可以讓我有 memory 泄漏:

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

然后我一直在檢查一些網站和stackoverflow問題,他們說應該這樣做:

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

    return unsubscribe();
  }, []);

這只是不調用 firebase.auth().onAuthChanged 方法。 有什么建議么?

非常感謝。

您的第二個示例實際上是調用返回的取消訂閱 function,然后返回該調用的結果(不返回任何內容)。 那是不對的。 您只想返回取消訂閱 function 本身,因此當不再需要觀察者時, 反應可以稍后調用它

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;
  }, []);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM