Firebase auth onAuthChange正确的使用方式



我试图使用firebase验证模块,但当我试图使它的工作与它的方法取消订阅它只是不会调用方法本身。我的第一个方法是没有退订方法,工作,但可能使我有内存泄漏:

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

然后我检查了几个网站和stackoverflow问题,他们说应该这样做:

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

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

非常感谢。

第二个示例实际上是调用返回的退订函数,然后返回该调用的结果(该函数不返回任何结果)。这是不对的。你只需要返回unsubscribe函数本身,以便react可以在以后不再需要观察者时调用它:


// The new way of doing this is:
import { getAuth } from "firebase/auth";
import { onAuthStateChanged } from "firebase/auth";

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

相关内容

最新更新