javascript - 在 addEventListener 调用的函数中删除 eventHandler

标签 javascript reactjs addeventlistener

我在我的页面上添加了无限滚动功能。它在 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);
        }
    }
};

enter image description here

最佳答案

removeListener 需要它在 addListener 时使用的相同函数引用。将代码更改为 addEventListener 之类的

this.scrollListener = window.addEventListener("scroll", this.handleScroll);

关于javascript - 在 addEventListener 调用的函数中删除 eventHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54687724/

相关文章:

php - 如何知道用户提交表单的确切时间

javascript - 禁用过渡动画

javascript - 将 promise polyfill 添加到 ES6

javascript放大img

angular - ios 模拟器中出现 ionic /Angular FileReader 错误(addEventListener 不是函数)

javascript - 从浏览器 JS 向 AWS Cognito 用户池进行身份验证

javascript - 无法读取未定义的属性 'indexOf'

javascript - 首先将 React 组件编写为一个 HTML 文件,然后将它们转换为组件是不是更好?

javascript - 更新状态时,map 不是函数

javascript - 将事件监听器添加到使用 javascript 创建的 <li>