繁体   English   中英

移除滚动监听器 reactjs

[英]Remove scroll listener reactjs

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

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 })
    }
}

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

所以你实际上并没有添加 this.listenToScroll,而是实际上添加了一个完全不同的 function。 (您没有参考)。

也许您可以使用变量来存储去抖版本。

this.debouncedListener = debounce(listenToScroll, 500);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM