函数已卸载但仍在eventlistener上执行

时间:2017-05-23 11:19:05

标签: javascript reactjs react-native

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

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

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

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

1 个答案:

答案 0 :(得分:4)

您的代码中存在轻微的混淆

 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
    }