【发布时间】:2019-02-14 10:02:04
【问题描述】:
我在页面中添加了无限滚动功能。它在 componentDidMount 生命周期钩子中附加了一个事件侦听器,当没有“nextlink”时,我想在事件侦听器调用的操作中删除它。我设置了一个可以正常工作的 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);
}
}
};
【问题讨论】:
-
执行
console.log(hasMoreLink)时记录了什么? -
只要还有数据要获取,它就会记录链接以获取下一批结果。来自微软的 api。之后它将不返回任何内容,并且 console.log(''remove event handler) 将执行。我将更新我的帖子以添加屏幕截图。
标签: javascript reactjs addeventlistener