如何在React中删除新的firebase onAuthStateChanged侦听器 [英] How to remove the new firebase onAuthStateChanged listener in react

查看:73
本文介绍了如何在React中删除新的firebase onAuthStateChanged侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用react-router在React Web应用程序中实现Firebase身份验证.

I'm implementing firebase auth in a react web app with react-router.

用户使用弹出式窗口登录使用Facebook或Google(在/signin处)登录,如果成功,我将路由到主应用程序(/).在主应用程序组件中,我侦听身份验证状态更改:

A user signs in (at /signin) with either Facebook or Google using the popup sign in, then if successful I route to the main app (/). In the main app component I listen for an auth state change:

  componentWillMount() {
    this.authListener = this.authListener.bind(this);
    this.authListener();
  }

authListener侦听auth更改:

authListener listens for the auth change:

authListener() {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        console.log('user changed..', user);
        this.setState({
          User: {
            displayName: user.displayName
          }
        });
      } else {
        // No user is signed in.
        browserHistory.push('/signin');
      }
    });
  }

一切正常,除非我退出(然后返回/signin)并再次使用facebook或google登录.然后我收到一条错误消息:

Everything works fine, except when I sign out (and go back to /signin) and sign in again using facebook or google. Then I get an error saying:

警告:setState(...):只能更新已安装的或正在安装的 组件.

Warning: setState(...): Can only update a mounted or mounting component.

我怀疑现在已卸载的先前已登录状态应用程序中的onAuthStateChanged侦听器仍在运行.

I suspect that the onAuthStateChanged listener from the now unmounted previous logged in state app is still running.

在卸载应用程序组件时,是否可以删除onAuthStateChanged侦听器?

Is there a way to remove the onAuthStateChanged listener when the App component unmounts?

推荐答案

您设置的所有侦听器也都必须拆除.

Any listeners that you have set up will also need to be torn down.

您的怀疑非常真实.

您应该使用 componentWillUnmount 生命周期方法来删除所有剩余的监听器可能会污染您的应用.

You should use the componentWillUnmount lifecycle method to remove any leftover listeners that might pollute your app.

要清除侦听器,请使用以下相关代码:

To clear up the listener, here's the relevant code:

authListener函数内部,您需要保存对组件内部侦听器的引用(由于调用firebase.auth().onAuthStateChanged而返回给您).这将是一个钩子,它将取消引用侦听器并将其删除.

Inside your authListener function you need to save a reference to the listener inside your component (it is returned to you as a result of calling firebase.auth().onAuthStateChanged). It will be a hook that will un-reference the listener and remove it.

因此,不仅要调用它,还要这样保存返回的值

So instead of just calling it, save the returned value as such

this.fireBaseListener = firebase.auth().onAuthStateChanged ...

然后在卸载组件时,使用以下代码:

And when your component un-mounts, use this code:

componentWillUnmount() {
   this.fireBaseListener && this.fireBaseListener();
   this.authListener = undefined;
}

这篇关于如何在React中删除新的firebase onAuthStateChanged侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆