在Unmount React上删除事件监听器 [英] Remove Event Listener On Unmount React

查看:317
本文介绍了在Unmount React上删除事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有更高级别的组件反应如下:

I had higher order component in react like this:

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包装的组件后,他们仍在抛出错误(当我滚动时):

After unmounting the component which are been wrapped via InfiniteScrolling, they where still throwing the error like (when I did scrolling):


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

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

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

Even though I did remove the scroll event on my component unmount. It didn't work.

但当我将代码改为这样时:

But when I changed the code to like this:

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

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

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

一切似乎都运转正常,没有任何问题。

everything seems to be working fine, without any issues.

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

I feel they are exactly the same thing, but the second one works fine while the first one was throwing up the error in the console as mentioned before!

推荐答案

您始终在创建新功能

    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);
    }

这篇关于在Unmount React上删除事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆