Remove Event Listener On Unmount React

后端 未结 4 1515
眼角桃花
眼角桃花 2020-12-02 22:16

I had higher order component in react like this:

export default function (InnerComponent) {
    class InfiniteScrolling extends React.Component {

        co         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 22:54

    .bind always creates a new function so you need to do like below, so it adds and removes the same function.

        constructor(props){
            super(props);
            this.onScroll = this.onScroll.bind(this); //bind function once
        }
    
        componentDidMount() {
            window.addEventListener('scroll', this.onScroll, false);
        }
    
        componentWillUnmount() {
            // you need to unbind the same listener that was binded.
            window.removeEventListener('scroll', this.onScroll, false);
        }
    

提交回复
热议问题