繁体   English   中英

在卸载 React 时删除事件侦听器

[英]Remove Event Listener On Unmount React

我在反应中具有更高阶的组件,如下所示:

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

        constructor(props){
            super(props);
        }

        componentDidMount() {
            window.addEventListener('scroll', this.onScroll.bind(this), false);
        }

        componentWillUnmount() {
            window.removeEventListener('scroll', this.onScroll.bind(this), false);
        }

        onScroll() {
            if ((window.innerHeight + window.scrollY) >= (document.body.offsetHeight - 50)) {
                const { scrollFunc } = this.props;
                scrollFunc();
            }
        }

        render() {
            return <InnerComponent {...this.props} />;
        }
    }

    InfiniteScrolling.propTypes = {
        scrollFunc: PropTypes.func.isRequired
    };

    return InfiniteScrolling;
}

卸载通过InfiniteScrolling包装的组件后,它们仍然抛出错误,例如(当我滚动时):

警告:setState(...):只能更新已安装或正在安装的组件。 这通常意味着您在未安装的组件上调用了 setState()。 这是一个无操作。 请检查未定义组件的代码。

即使我确实删除了组件卸载上的scroll事件。 它没有用。

但是当我把代码改成这样时:

constructor(props){
    super(props);
    this.onScroll = this.onScroll.bind(this);
}

componentDidMount() {
    window.addEventListener('scroll', this.onScroll, false);
}

componentWillUnmount() {
    window.removeEventListener('scroll', this.onScroll, false);
}

一切似乎都运行良好,没有任何问题。

我觉得它们完全一样,但是第二个工作正常,而第一个在控制台中抛出了前面提到的错误!

.bind总是创建一个新函数,所以你需要像下面那样做,所以它添加和删除相同的函数。

    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);
    }
      componentDidMount() {
            window.addEventListener('scroll', this.onScroll, false);
        }

        componentWillUnmount() {
            window.removeEventListener('scroll', this.onScroll, false);
        }
        // use arrow function instead
        onScroll = () => { 
            if ((window.innerHeight + window.scrollY) >= (document.body.offsetHeight - 50)) {
                const { scrollFunc } = this.props;
                scrollFunc();
            }
        }

或者你可以使用箭头函数来解决 .bind(this) 问题,它工作得很好。

我知道有点晚了,但我刚刚遇到这个问题,想与您分享我的解决方案,期待任何反馈。 该解决方案包括react hooks 我希望你喜欢

// Declare a static listener.
const eventListeners = useRef();

// now let's create our scroll Handler
const scrollHandler = useCallback(() => {...},[]);

useEffect(() => {
   // Here will be removing the static listener and then updated it for 
   // our new one since the first time will be empty it won't do anything.
    window.removeEventListener('scroll', eventListeners.current, true);

    // Then will set our current scroll handler to our static listener
    eventListeners.current = scrollHandler;

    // Here will be adding the static listener so we can keep the reference
    // and remove it later on
    window.addEventListener('scroll', eventListeners.current, true);
},[scrollHandler]);

带有箭头函数和无绑定的我的项目的工作版本:

componentDidMount = () => {
  window.addEventListener("wheel", this.onScroll, false);
};

componentWillUnmount() {
  window.removeEventListener("wheel", this.onScroll, false);
}

onScroll = (e) => {
  const item = this.refs.myElement;
  if (e.deltaY > 0) item.scrollLeft += 200;
  else item.scrollLeft -= 200;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM