删除滚动侦听器reactjs

时间:2020-05-05 20:14:49

标签: reactjs

在安装时,我添加了事件监听器,而在卸载时,可以正常工作。但是没有用的是当我的数据库中没有更多行时,我想停止提取调用。它不会删除事件侦听器,但会导致无限次获取,但应避免使用它。

componentDidMount() {
    window.addEventListener("scroll", debounce(this.listenToScroll, 500), true)
}

componentWillUnmount() {
    window.removeEventListener("scroll", this.listenToScroll, true)
}

loader = () => {
    const { showLoader } = this.state

    const { page, isLoading, count, data } = this.props.load
    const noMoreResults = <h5>No More Results</h5>
    const loader = !isLoading && count === data.length ? noMoreResults :
        showLoader ?
            <Loader
                type="ThreeDots"
                color="#00BFFF"
                height={80}
                width={80}
                timeout={10000} //3 secs
            /> : null

    if (loader === noMoreResults) {
        console.log("true") {/*I get inside here but it isn't removing the event listener?*/}
        window.removeEventListener("scroll", this.listenToScroll, true)
    }
    return loader
}

listenToScroll() {
    console.log("im inside!!")
    if (window.innerHeight + window.pageYOffset  >= (window.document.body.scrollHeight - 500)) {
        this.setState({ page: this.state.page + 1, change: !this.state.change, showLoader: true })
    }
}

1 个答案:

答案 0 :(得分:1)

问题在于,当您在挂载上添加事件侦听器时,您正在使用debounce()方法。

因此,您实际上并没有添加this.listenToScroll,而是实际上添加了一个完全不同的功能! (您没有参考)。

也许您可以使用一个变量来存储反跳版本。

this.debouncedListener = debounce(listenToScroll, 500);

window.addEventListener("scroll", this.debouncedListener, true)

window.removeEventListener("scroll", this.debouncedListener, true)