简体   繁体   English

功能已卸载但仍在事件监听器上执行

[英]Function unmounted but still executing on 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
    }

Try this 尝试这个

 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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM