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

应用程式:

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


但是是行不通的。

最佳答案

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

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

10-07 17:40