reactjs removeListener不能与es6类一起使用

时间:2016-02-17 17:34:41

标签: reactjs

在窗口上删除事件侦听器不起作用,几乎就像添加和删除它时的功能不同一样。关于如何解决这个问题的想法?我还试图在文件中的类及上面抽象onScroll方法,也没有运气。

componentDidMount() {
    if (__CLIENT__) {
      window.removeEventListener('scroll', this.onScroll.bind(this), true);
      console.log('mounting')
      window.addEventListener('scroll', this.onScroll.bind(this), true);
    }
  }

  componentWillUnmount() {
    console.log('unmount');
    if (__CLIENT__) {
      window.removeEventListener('scroll', this.onScroll.bind(this), true);
    }
  }

  onScroll() {
    const { isLoading, isEndOfSurah } = this.props;
    console.log('here');

    if (isEndOfSurah) {
      return false;
    }

    if (!isLoading && !this.state.lazyLoading && window.pageYOffset > (document.body.scrollHeight - window.innerHeight - 1000)) {
      // Reached the end.
      this.setState({
        lazyLoading: true
      });

      this.lazyLoadAyahs();
    }
  }

1 个答案:

答案 0 :(得分:2)

我会详细说明我的评论。 this.onScroll.bind(this)返回一个新函数,因此用于每个ad​​d / remove的每个this.onScroll.bind(this)在内存中都是一个不同的函数。您可以使用===相等运算符来测试它。相反,在构造函数中绑定onScroll函数:

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

然后只使用this.onScroll,因为它将具有所需的此绑定,并且将是每个事件侦听器中引用的相同函数。

相关问题