reactjs - react : Disconnecting firebase ref on componentWillUnMount

标签 reactjs firebase

当用户在单页应用程序中更改 View 时,我想断开 Firebase 引用的连接。当所述用户更改 View 时,我想获得对 firebase 的新引用,因为我只想要过滤数据,并且每个 View 过滤不同的数据。

当我更改 View 并更新一些数据时,就会出现问题。然后 react 会引发以下错误:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.

此错误在尝试更新未安装的组件时引用了其他 View 。这种情况不应该发生,因为我关闭了 componentWillUnMount 上的引用

在这两个 View 中,我都有以下用于获取新引用的代码:

componentDidMount() {
    // I have declared this.ref on the constructor so I can call off() on componentWillUnMount
    this.ref = firebase.database().ref().child('mainNode').orderByChild('someProperty').equalTo('someValue');

    this.ref.on('value', (snap) => {
      let values = [];
      snap.forEach((child) => {
        let value = child.val();
        let key = child.key;
        const valueWithKey = update(value, {$merge: {key}});
        values.push(valueWithKey);
      });
      // This is the offending line
      this.setState({data: values});
    });
  }

这是我的 componentWillUnMount 代码:

componentWillUnMount() {
    this.ref.off();
    // I have also tried goOffline()
}

我做错了什么?

最佳答案

事实证明,正确的生命周期 Hook 名为 componentWillUnmount 而不是 componentWillUnMount,这导致 React 无法执行该函数。

关于reactjs - react : Disconnecting firebase ref on componentWillUnMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42389617/

相关文章:

javascript - React Js,this.context 在构造函数方法中未定义

javascript - 使用 JavaScript immutability-helper 或 {...data, } 更新数据集合中一条记录的一个字段

node.js - AWS 上的实时数据库

python - 在 python 中操作 Google Cloud Firestore 数据

android - Kotlin - Firebase 和 Glide - 获取图像 url,以便 glide 可以使用它

swift - 下载期间在 firebase 上请求多个值 [Swift]!

ios - Firebase for iOS 内部框架

java - 选择图片并裁剪后如何将个人资料图片更新为 firebase?

javascript - 使用 Highcharts-React 拖放不起作用

javascript - react 得到所有 child 的引用