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

IT技术 javascript reactjs react-native
2021-05-05 06:17:25

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

   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个回答

您的代码中有轻微的混乱

 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
    }