[英]Should we be using the unsubscribe method returned by Auth.onAuthStateChanged() in firebase to clean up memoery leaks?
[英]Firebase onAuthStateChanged unsubscribe recursion
我有這段代碼可以檢查用戶是否已經在Firebase中登錄,如果已經登錄,請使用Redux調度操作並將狀態更新為當前的auth用戶。
/**
* check to see if the user has signed in already or not
*/
function initAuth(dispatch) {
return new Promise((resolve, reject) => {
const unsubscribe = firebase.auth().onAuthStateChanged(
authUser => {
dispatch({ type: "INIT_AUTH", payload: authUser });
unsubscribe();
resolve();
},
error => reject(error)
);
});
}
initAuth(store.dispatch)
.then(() => render())
.catch(error => console.error(error));
我感到困惑的是,為什么在unsubscribe中調用unsubscribe()? 我知道您可以像在JavaScript遞歸中那樣進行操作,但是這里有什么用? 謝謝!
onAuthStateChanged
采用一個函數,因為它是唯一的參數。 該函數是在auth狀態更改時將被調用的函數。 所以代碼
function printHelloWorld() {
console.log("Hello World")
}
firebase.auth().onAuthStateChanged(printHelloWorld)
每當身份驗證狀態更改時,都會在控制台上打印"Hello World"
。 但是,稍后,我們希望不再執行該函數,因為我們已經完成了所需的任何操作。 如果您熟悉事件偵聽器,則它們會使用一種模式來刪除事件偵聽removeEventListener
,您將調用removeEventListener
東西。 但是offAuthStateChanged
沒有offAuthStateChanged
或類似的東西。 而是onAuthStateChanged
函數向您返回一個函數,該函數取消訂閱您最初給它的函數 。 需要明確的是,它不會返回原始函數(您給了它的那個函數,因此在此示例中為printHelloWorld
),而是返回了一個可用於刪除原始函數的新函數。
回到示例:
function printHelloWorld() {
console.log("Hello World")
}
var unsubscribe = firebase.auth().onAuthStateChanged(printHelloWorld)
// ... Sometime later when we are no longer interested in auth changes
unsubscribe();
// From this point forward, when the auth state changes, printHelloWorld will no longer be triggered.
最后,假設您只想讓一個函數在auth更改上運行,但只運行一次 。 最簡單的方法是先運行一次,然后取消訂閱。 所以代碼:
var unsubscribe = firebase.auth().onAuthStateChanged(() => {
console.log("Hello World")
unsubscribe()
})
意味着第一次身份驗證狀態更改時,我們將記錄該字符串,然后立即取消訂閱進一步的更改。 因此,通過在函數內部調用取消訂閱,我們只是說,運行一次,然后刪除自己。
另外,請注意,您可以在函數的開頭或結尾調用取消訂閱,這沒關系。 整個函數主體將像其他函數一樣執行。 因此,調用unsubscribe不會停止執行該函數的其余部分,或者類似的事情。
這就是為什么像
var unsubscribe = firebase.auth().onAuthStateChanged(() => {
unsubscribe()
// Lots of other code here...
});
是這樣的常見模式。
如果你想監聽的用戶只是一個時間 ,你必須這樣做,這樣的權威性地位的變化:
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if(unsubscribe) {
unsubscribe();
}
}
偵聽器似乎運行兩次,第一次是在創建時,第二次是在用戶實際更改其狀態時。 第一次沒有定義unsubscribe
因此您在運行前檢查是否已定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.