javascript - 函数已卸载但仍在事件监听器上执行

标签 javascript reactjs react-native

我已经卸载了绑定(bind)到窗口事件监听器的函数。仍然,在转到下一页后,事件中的函数虽然被删除了,但仍然执行?这可能是什么问题?

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

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

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

最佳答案

你的代码有点困惑

 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
    }

关于javascript - 函数已卸载但仍在事件监听器上执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44133311/

相关文章:

reactjs - 如何在 React Native 中包装 Flatlist 项目

react-native - 为什么 Dimensions.get ('window' ).height 在 iOS 上返回 0?

javascript - 在 typescript 中,拥有像这样的对象属性 "{ [x: string]: any }"意味着什么?

javascript - 从 JSON 数组 react TreeView

javascript - 映射到数组对象中,并带有其他映射参数的索引

reactjs - 不再支持此 SVGO 版本。升级到 v2.x.x

react-native - 如何在 Detox 中添加像 not.toHaveText 这样的否定断言?

javascript - 文本输入 fadeToggle jQuery 问题

javascript - 将字符串转换为 Angular 8 中的枚举值

javascript - Angular UI 树 - 只允许拖放到第二级(子节点)