Firebase 9,實時資料庫/與 expo 原生反應。
問題:我無法取消訂閱 firebase RTD onChange 事件偵聽器。
檔案說:“在父偵聽器上呼叫 off() 不會自動洗掉在其子節點上注冊的偵聽器;還必須在任何子偵聽器上呼叫 off() 以洗掉回呼。” Firebase 檔案
錯誤:當我嘗試.off在參考上使用時,我得到reference.off() is not a function
const db = getDatabase();
const reference = ref(db, "users/" props.userId);
const updateScore = (snapshot) => {
if (snapshot.val() !== null) setHighScore(highscore);
};
useEffect(() => {
if (props.userId === "") props.navigation.navigate("Auth");
else onValue(reference, updateScore);
// throws error reference.off() is not a function
return () => reference.off();
}, [props.userId]);
我也試著reference.unsubscribe()與reference.removeEventListener(updateScore)沒有運氣。它們都觸發了相同的錯誤reference.**** is not a function。
如果不清除此事件偵聽器,我的應用程式就會出現記憶體泄漏。
uj5u.com熱心網友回復:
對于V9,當你呼叫onValue回傳的退訂功能,如圖所示的參考檔案進行onValue。所以要取消訂閱:
useEffect(() => {
if (props.userId === "") props.navigation.navigate("Auth");
else return onValue(reference, updateScore);
}, [props.userId]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375813.html
