代码之家  ›  专栏  ›  技术社区  ›  sosick

路径应用程序更改时如何停止滚动事件?

  •  0
  • sosick  · 技术社区  · 6 年前

    我正在创建一个带有无限卷轴的简单照片库。问题是,当我单击链接并更改路径时,活动仍然存在,这会给我带来错误。

    应用程序:

    componentDidMount() {
      this.scrollListener = window.addEventListener("scroll", this.handleScroll);
    }
    
    handleScroll = () => {
      const { scrolling, totalPages, page } = this.state;
      if (scrolling || totalPages <= page) {
        return;
      }
      const lastPhoto = document.querySelector("section > div:last-child");
      const lastPhotoOffset = lastPhoto.offsetTop + lastPhoto.clientHeight;
      const pageOffset = window.pageYOffset + window.innerHeight;
      const bottomOffset = 20;
      if (pageOffset > lastPhotoOffset - bottomOffset) {
        this.loadMorePhotos();
      }
    

    如果事件至少发生过一次,我转到/photo/photo:id路径,我会得到一个错误:

    TypeError: Cannot read property 'offsetTop' of null
    const lastPhotoOffset = lastPhoto.offsetTop + lastPhoto.clientHeight;
    

    我试过:

    componentWillUnmount() {
      this.handleScroll = null;
    }
    

    或:

    componentWillUnmount() {
      this.scrollListener = null;
    }
    

    但不起作用。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Piyush Zalani    6 年前

    删除componentwillunmount中的事件侦听器:

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