javascript - React Native 无法对未安装的组件 firebase 执行 React 状态更新

标签 javascript firebase react-native firebase-realtime-database

我有这段代码可以在添加新 child 时监听实时数据库中的变化。

mUserRef = firebase.database().ref("Messages").child(conversation);
mUserRef.on("child_added", snapshot => {
    const message = {
        key: snapshot.key,
        ...snapshot.val()
    };
    this.onReceive(message);
});

当接收到添加到数据库中的新 child 时,将触发此代码 ref

let cy = this;
        firebase
        .database()
        .ref("LastMessages")
        .child(key)
        .once("value")
        .then(function(snapshot) {
            //...some code
        }); 

问题是当我使用 componentWillUnmount 时我无法取消订阅实时监听器

取消订阅代码

constructor(props) {
    super(props);
    this.state = {
      ready: false,
      messages: []
    };
  }
  _isMounted = false;


componentDidMount = async () => {
    this._isMounted = true;
}

  async retriveMessages(conversation) {
    let cy = this;

    cy.setState({
      ready: true
    });
    let mUserRef = null;
    if (this._isMounted) {
      mUserRef = firebase
        .database()
        .ref("Messages")
        .child(conversation);

      mUserRef.on("child_added", snapshot => {
        const message = {
          key: snapshot.key,
          ...snapshot.val()
        };
        this.onReceive(message);
      });
    } else {
      mUserRef.child(conversation).off("child_added");
    }
  }


  componentWillUnmount() {
    this._isMounted = false;
  }

我尝试过的解决方案:

Unsubscribing from Firebase Realtime Database

componentwillunmount to unsubscribe from firestore

how to remove firebase database listener...

How to stop Firebase Listener when i pass to another screen?

最佳答案

componentWillUnmount() :

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().

因此执行以下操作:

 componentWillUnmount() {
    mUserRef.off("child_added");
    this._isMounted = false;
  }

关于javascript - React Native 无法对未安装的组件 firebase 执行 React 状态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59172066/

相关文章:

javascript - 如何在 Firechat 中创建聊天室?

Firebase 函数 - 创建新文档时推送通知

javascript - 错误 : `fsevents` unavailable (this watcher can only be used on Darwin)

javascript - 使用 V8 而不是 JavascriptCore 进行 React-Native

javascript - React Native 将 http 图像保存到 Android 相机胶卷

javascript - 查找将按钮设置为焦点的脚本

javascript - 我的应用程序在设备上运行缓慢是因为我使用的图像以及如何删除硬编码的宽度和高度

javascript - Android:即使使用 setJavaScriptEnabled(true) 也无法让 javascript 在 WebView 上工作

javascript - 在 React 中使用 props 或 deconstruction 定义用户

firebase - 从 Firebase 控制台检索注册的 token