防抖功能未启动

时间:2019-05-09 12:14:07

标签: javascript reactjs debouncing

我在componentDidMount中有以下代码,像这样:

    if (setNavigationSections) {
        setNavigationSections(filteredFieldGroups);
        window.addEventListener('scroll', debounce(50, this.handleOnScroll)));
    }  

我现在将其更改为:

    if (setNavigationSections) {
        setNavigationSections(filteredFieldGroups);
        window.addEventListener('scroll', e =>  debounce(50, this.handleOnScroll(e)));
    }  

以便我可以检测到handleScroll中的滚动方向:

handleOnScroll = e => {
    const {navigationSections, setNavigationSectionActive} = this.props;
    const OFFSET_TOP = 0;
    const window = e.currentTarget;

    if(this.prev > window.scrollY){
        const reversedSections = this.getReversedNavigationSections();

        reversedSections.forEach(section => {
            if (document.getElementById(section.id).getBoundingClientRect().top >= OFFSET_TOP) {
                setNavigationSectionActive(section.id);
            }
        });
    }
    else if(this.prev < window.scrollY){
        navigationSections.forEach(section => {
            if (document.getElementById(section.id).getBoundingClientRect().top <= OFFSET_TOP) {
                setNavigationSectionActive(section.id);
            }
        });
    }

    this.prev = window.scrollY;
}

和去抖动功能是:

const debounce = (delay, fn) => {
    let timerId;
    return function (...args) {
        if (timerId) {
            clearTimeout(timerId);
        }

        timerId = setTimeout(() => {
            fn(...args);
            timerId = null;
        }, delay);
    }
}

但是防抖功能不再起作用。

0 个答案:

没有答案