我正在创建一个带有无限卷轴的简单照片库。问题是,当我单击链接并更改路径时,活动仍然存在,这会给我带来错误。
应用程序:
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;
}
但不起作用。