我在我的页面上添加了无限滚动功能。它在 componentDidMount 生命周期 Hook 中附加了一个事件监听器,我想在没有“下一个链接”时在事件监听器调用的操作中将其删除。我设置了一条运行良好的 console.log() 消息,但我不确定为什么 window.removeEventListener() 函数不起作用。任何帮助将不胜感激。
一段代码负责添加/删除 eventListener。
componentDidMount() {
this._isMounted = true;
this.props.onFetchTeams();
this.scrollListener = window.addEventListener("scroll", e => {
this.handleScroll(e);
});
}
handleScroll = () => {
const hasMoreLink = this.props.teams["@odata.nextLink"];
if (hasMoreLink == "") {
console.log("remove event handler");
window.removeEventListener("scroll", this.handleScroll);
}
// If there is at least a team and is currently not loading, proceed to load more.
if (this.state.loadingMore === false && this.props.teams["value"]) {
// get the last teamcard in the page
const lastTeam = document.querySelector(
".team-card-wrapper:last-of-type"
);
// get the height of the current team, and get the height of the current position on screen.
const lastTeamOffset = lastTeam.offsetTop + lastTeam.clientHeight;
const pageOffset = window.pageYOffset + window.innerHeight;
// the range that teams will load earlier than the bottom of the page.
const bottomOffset = 30;
if (pageOffset > lastTeamOffset - bottomOffset) {
this.setState({ loadingMore: true });
this.props.onFetchMoreTeams(hasMoreLink);
}
}
};
最佳答案
removeListener
需要它在 addListener
时使用的相同函数引用。将代码更改为 addEventListener 之类的
this.scrollListener = window.addEventListener("scroll", this.handleScroll);
关于javascript - 在 addEventListener 调用的函数中删除 eventHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54687724/