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

时间:2019-01-17 10:13:43

标签: javascript reactjs

我正在创建一个无限滚动的简单照相馆。问题是,当我单击“链接并更改路径”时,事件仍然存在,但我却出错了。

应用程序:

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 个答案:

答案 0 :(得分:2)

删除componentWillUnmount内部的事件侦听器:

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