在addEventListener调用的函数中删除eventHandler

时间:2019-02-14 10:02:04

标签: javascript reactjs addeventlistener

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

enter image description here

3 个答案:

答案 0 :(得分:2)

removeListener需要与addListener相同的功能引用。将代码更改为addEventListener之类的

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

答案 1 :(得分:0)

考虑通过直接传递handleScroll函数来修改添加滚动事件处理程序的方式:

componentDidMount() {
    this._isMounted = true;
    this.props.onFetchTeams();

    /* 
    With the this.handleScroll bound to this class instance, we can now pass the method 
    directly to addEventListener as shown
    */
    this.scrollListener = window.addEventListener("scroll", this.handleScroll);
}

handleScroll = () => {
    const hasMoreLink = this.props.teams["@odata.nextLink"];

    if (hasMoreLink == "") {
        console.log("remove event handler");
        /* This will now work as expected */
        window.removeEventListener("scroll", this.handleScroll);
    }

    /* Rest of your code remains unchanged .. */
}

答案 2 :(得分:0)

这是因为提供给addEventListener的函数和提供给removeEventListener的函数应该完全相同,但是在您的情况下,您将为addEventListener创建一个新的箭头函数。所以我认为您应该尝试这样的事情:

this.scrollListener = window.addEventListener("scroll", this.handleScroll)
...
handleScroll = (e) => {
    ...
    if(noMoreScroll) window.removeEventListener("scroll", this.handleScroll)
    ...
}

希望对您有所帮助:)