代码之家  ›  专栏  ›  技术社区  ›  j.doe BudgieInWA

我无法在React中分离firebase侦听器

  •  0
  • j.doe BudgieInWA  · 技术社区  · 7 年前

    我想在组件卸载但找不到解决方案时分离侦听器。每当我在卸载组件后进行更改时,结果都会显示在浏览器控制台中。

    数据库

    var groupUpdate = function(id, callback) {
        return firebase.database().ref('groups/').child(id).on('child_changed', (snapshot) => {
            callback({key: snapshot.key, value: snapshot.val()});
        });
    };
    
    module.exports = {
        groupUpdate: groupUpdate
    }
    

    组成部分

    export default class Example extends React.Component {
        constructor(props) {
            super(props);
    
            this.groupListener = database.groupUpdate(this.props.group.id, (result) => {
                console.log(result);
            }).bind(this);
        }
    
        componentWillUnmount() {
            this.groupListener = null;
        }
    
        render() {
            ....
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Frank van Puffelen    7 年前

    阻止与您连接的侦听器 on('child_changed' 呼叫 off('child_changed' 在同一引用或查询上。

    因此:

    componentWillUnmount() {
      firebase.database().ref('groups/').child(id).off('child_changed');        
    }
    

    或者,如果希望只注销在此代码中共享的特定侦听器,请执行以下操作:

    componentWillUnmount() {
      firebase.database().ref('groups/').child(id).off('child_changed', groupUpdate);        
    }