Use of window.addEventListener and window.removeEventListener in react

In the process of writing code, I found that the native event
window.addEventListener is bound to the react’s tsx. The current page can listen to the event, and other pages can also listen to the event. This will cause problems. For example, page A listens to scrolling events, page B does not need Scrolling events are monitored, but page B will also be triggered, and a bug will occur at this time.
The correct approach is to clear the monitoring event when the page is unloaded after the event is bound to the A page.

 constructor(props) {
    
    
    super(props);
    this.scrollHandler = this.handleScroll.bind(this);
  }
componentDidMount() {
    
    
    window.addEventListener('scroll', this.scrollHandler);
  }
  componentWillUnmount(){
    
    
    window.removeEventListener('scroll',this.scrollHandler);
  }
  handleScroll = () =>{
    
    
    let scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
    this._handleScroll(scrollTop);
  }
  _handleScroll = (scrollTop) =>{
    
    
	//dosomething
  }

Guess you like

Origin blog.csdn.net/sunzhen15896/article/details/110313031