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

查看:23
本文介绍了如何在反应中删除新的 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.

有没有办法在 App 组件卸载时移除 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;
}

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

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