Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何正确分离firebase db子事件侦听器?_Javascript_Reactjs_Firebase_Firebase Realtime Database - Fatal编程技术网

Javascript 如何正确分离firebase db子事件侦听器?

Javascript 如何正确分离firebase db子事件侦听器?,javascript,reactjs,firebase,firebase-realtime-database,Javascript,Reactjs,Firebase,Firebase Realtime Database,我正在尝试分离此侦听器: listenForNew() { const firebase = this.props.firebase; let newestDate = new Date().getTime(); if(this.state.subitiq.length !== 0) { newestDate = this.state.subitiq[this.state.subitiq.length-1].date; } console.

我正在尝试分离此侦听器:

listenForNew() {
    const firebase = this.props.firebase;
    let newestDate = new Date().getTime();
    if(this.state.subitiq.length !== 0) {
        newestDate = this.state.subitiq[this.state.subitiq.length-1].date;
    }
    console.log("listening after date " + (newestDate+1));
    const ref = firebase.database().ref().child('subitiq').orderByChild('date').startAt(newestDate+1).on('child_added', snapshot => {
        console.log("added new subitie with key " + snapshot.key);
        let subitie = snapshot.val();
        subitie.key = snapshot.key;
        let subitiq = this.state.subitiq.slice(0);
        subitiq.push(subitie);
        let showedSubitiq = this.state.showedSubitiq.slice(0);
        showedSubitiq.push(subitie);
        this.setState({subitiq: subitiq, showedSubitiq: showedSubitiq});
        //console.log(subitie);
    }, error => {
        console.error(error);
    });

    this.addRefListener(ref, 'subitiq', 'child_added');
} // listenForNew()
const ref = firebase.database().ref().child('subitiq').orderByChild('date').startAt(newestDate+1).on('child_added', snapshot =>
这是addRefListener():

这就是我试图分离的方式:

    componentWillUnmount() {
        this.componentCleanup();
        window.removeEventListener('beforeunload', this.componentCleanup); // remove the event handler for normal unmounting
    }
    componentDidMount() {
        window.addEventListener('beforeunload', this.componentCleanup);
//...
}
    componentCleanup() { // this will hold the cleanup code
        // whatever you want to do when the component is unmounted or page refreshes
        const firebase = this.props.firebase;
        for(let i=0; i<this.state.refs.length; i++) {
            try {
                firebase.database().ref().child(this.state.refPaths[i]).off(this.state.listeners[i]);
                console.log("removed listener at '" + this.state.refPaths[i] + "' on '" + this.state.listeners[i] + "' #1 block");
            } catch(er) {
                console.log("error block #1");
                console.error(er);
            }

            try {
                firebase.database().ref().child(this.state.refPaths[i]).off(this.state.listeners[i], this.state.refs[i]);
                console.log("removed listener at '" + this.state.refPaths[i] + "' on '" + this.state.listeners[i] + "' #2 block");
            } catch(er) {
                console.log("error block #2");
                console.error(er);
            }

            try {
                this.state.refs[i].off(this.state.listeners[i]);
                console.log("removed listener at '" + this.state.refPaths[i] + "' on '" + this.state.listeners[i] + "' #3 block");
            } catch(er) {
                console.log("error block #3");
                console.error(er);
            }
        }
    }
componentWillUnmount(){
this.componentCleanup();
window.removeEventListener('beforeunload',this.componentCleanup);//删除事件处理程序以进行正常卸载
}
componentDidMount(){
window.addEventListener('beforeunload',this.componentCleanup);
//...
}
componentCleanup(){//这将保存清理代码
//卸载组件或刷新页面时,您希望执行的任何操作
const firebase=this.props.firebase;
for(设i=0;i
通过将单个侦听器作为参数传递给off(),可以删除该侦听器。在不带参数的位置调用off(),将删除该位置的所有侦听器

例如,如果您有此侦听器:

listenForNew() {
    const firebase = this.props.firebase;
    let newestDate = new Date().getTime();
    if(this.state.subitiq.length !== 0) {
        newestDate = this.state.subitiq[this.state.subitiq.length-1].date;
    }
    console.log("listening after date " + (newestDate+1));
    const ref = firebase.database().ref().child('subitiq').orderByChild('date').startAt(newestDate+1).on('child_added', snapshot => {
        console.log("added new subitie with key " + snapshot.key);
        let subitie = snapshot.val();
        subitie.key = snapshot.key;
        let subitiq = this.state.subitiq.slice(0);
        subitiq.push(subitie);
        let showedSubitiq = this.state.showedSubitiq.slice(0);
        showedSubitiq.push(subitie);
        this.setState({subitiq: subitiq, showedSubitiq: showedSubitiq});
        //console.log(subitie);
    }, error => {
        console.error(error);
    });

    this.addRefListener(ref, 'subitiq', 'child_added');
} // listenForNew()
const ref = firebase.database().ref().child('subitiq').orderByChild('date').startAt(newestDate+1).on('child_added', snapshot =>
然后,要分离它,您需要使用相同的引用并执行以下操作:

ref.off('child_added');
另外
off()
Reference


在下一行,由于函数的原因,您调用的
ref
对象不是引用/查询对象,而是快照回调函数(
snapshot=>{/*…*/}

const ref=firebase.database().ref().child('subitiq').orderByChild('date').startAt(newestDate+1).on('child_added',snapshot=>{/*…*/},error=>{/*…*/});
要获取引用/查询对象,必须将行拆分为以下几行:

let queryRef=firebase.database().ref().child('subitiq').orderByChild('date').startAt(newestDate+1);
让callback=queryRef.on('child_added',snapshot=>{/*…*/},error=>{/*…*/});
拥有这两个功能后,可以调用
addListenerUnsubscribe
,这是我的
addRefListener
函数版本

addListenerUnsubscribe(queryRef,'child_added',回调);
稍后清理组件时,只需调用
unsubscribeAllListeners()
,如下所示:

componentCleanup() {
  unsubscribeAllListeners();
}
addListenerUnsubscribe(ref,eventType,callback,name){
让侦听器=this.state.listeners;
push({ref:ref,eventType:eventType,cb:callback,name:name});
this.setState({listeners});//这似乎不必要
}
取消订阅AllListeners(){
让侦听器=this.state.listeners;
forEach((侦听器)=>{
listener.ref.off(listener.eventType,listener.callback);
});
this.setState({listeners:[]});
}
使用上述代码,如果需要,还可以按名称删除一组侦听器

取消订阅ListenerSByname(名称){
让侦听器=this.state.listeners;
让剩余=侦听器。筛选器((侦听器)=>{
如果(name!==listener.name)返回true;//保留
listener.ref.off(listener.eventType,listener.callback);
});
//剩下的是一个仍处于活动状态的侦听器数组
this.setState({listeners:remaining});
}
参考资料:


Wat是错误this.state.refs[i]。off不是一个函数