函数已卸载但仍在eventlistener上执行 [英] Function unmounted but still executing on eventlistener

查看:90
本文介绍了函数已卸载但仍在eventlistener上执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经卸载了绑定到窗口事件监听器的函数。仍然,在进入下一页后,事件内部的功能仍然执行,但被删除了吗?这可能是什么问题?

I've unmounted my function which is binded to the window event listener. Still, after going to the next page the function inside the event still executes although being removed? What might be the problem here?

   componentDidMount(){
     window.addEventListener("resize", this.updateDimensions.bind(this));
   }
   componentWillUnmount(){
     console.log("unmounting....");
     window.removeEventListener('resize', this.updateDimensions.bind(this));
   }

这是绑定附加到事件的函数:

Here is the function which is binded-attached to the event:

 updateDimensions(){
      if (this.refs.get_it.clientWidth < 774){
         this.setState({
         width:this.refs.get_it.clientWidth,
         height:400,
         flag:true});
      }
   }


推荐答案

那里您的代码中有轻微的混淆

there is slight confusion in your code

 componentDidMount(){
      window.addEventListener("resize", this.updateDimensions.bind(this)); 
      // first instance listening to event
    }
    componentWillUnmount(){
      console.log("unmounting....");
      window.removeEventListener('resize', this.updateDimensions.bind(this));
      // second instance removed from listener here first!== second
    }

试试这个

 constructor(props) {
      super(props);
      this.updateDimensions = this.updateDimensions.bind(this);
    }
    componentDidMount(){
      window.addEventListener("resize", this.updateDimensions);
      // first instance listening to event
    }
    componentWillUnmount(){
      console.log("unmounting....");
      window.removeEventListener('resize', this.updateDimensions);
      // same instance removed from listener here first == second
    }

这篇关于函数已卸载但仍在eventlistener上执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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