Javascript Firebase 停止监听 onAuthStateChanged
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37370224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Firebase stop listening onAuthStateChanged
提问by James Gilchrist
As of version ^3.0.0, I'm having a difficult time removing the auth state change listener.
从版本 ^3.0.0 开始,我很难删除身份验证状态更改侦听器。
To start the listener per the documentation:
要根据文档启动侦听器:
firebase.auth().onAuthStateChanged(function (user) {
// handle it
});
However, I cannot find anywhere in the documentation that refers to a remove auth state change listener. There is peculiar function on the Firebase.Auth class called removeAuthTokenListener
. Unfortunately it's not documented (firebase docs reference).
但是,我在文档中找不到任何提到删除身份验证状态更改侦听器的地方。Firebase.Auth 类上有一个特殊的函数,称为removeAuthTokenListener
. 不幸的是,它没有记录(firebase docs reference)。
Via your browser's web console.
通过浏览器的 Web 控制台。
var auth = firebase.auth();
auth.removeAuthTokenListener;
prints a function definition that takes one parameter. I tried to do the following:
打印一个接受一个参数的函数定义。我尝试执行以下操作:
this.authListener = firebase.auth().onAuthStateChanged(function (user) {...});
firebase.auth().removeAuthTokenListener(this.authListener);
but that didn't do anything.
但这没有做任何事情。
回答by Frank van Puffelen
According to the documentation, the onAuthStateChanged()
function returns
根据文档,该onAuthStateChanged()
函数返回
The unsubscribe function for the observer.
观察者的取消订阅功能。
So you can just:
所以你可以:
var unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
// handle it
});
And then:
进而:
unsubscribe();
回答by theGiantOtter
This has already been answered really well by Frank van Puffelen, but here is my use case for React components that are getting user data. These components need to unsubscribe when the component is unmounted or there will be a memory leak for each of these components.
Frank van Puffelen 已经很好地回答了这个问题,但这是我获取用户数据的 React 组件的用例。这些组件需要在卸载组件时取消订阅,否则每个组件都会出现内存泄漏。
React.useEffect(() => {
let unsubscribe;
const getUser = async () => {
unsubscribe = await firebase.checkUserAuth(user => setUser(user));
};
getUser();
return function cleanup() {
unsubscribe();
};
}, []);