简体   繁体   English

Firebase 停止监听 onAuthStateChanged

[英]Firebase stop listening onAuthStateChanged

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 . Firebase.Auth 类上有一个特殊的函数,称为removeAuthTokenListener Unfortunately it's not documented ( firebase docs reference ).不幸的是,它没有记录( 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.但这没有做任何事情。

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();

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. Frank van Puffelen 已经很好地回答了这个问题,但这是我获取用户数据的 React 组件的用例。 These components need to unsubscribe when the component is unmounted or there will be a memory leak for each of these components.这些组件需要在卸载组件时取消订阅,否则每个组件都会出现内存泄漏。

React.useEffect(() => {
  let unsubscribe;
  const getUser = async () => {
    unsubscribe = await firebase.checkUserAuth(user => setUser(user));
  };
  getUser();
  return function cleanup() {
    unsubscribe();
  };
}, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM