useEffect中的滚动事件不会重新初始化

时间:2020-11-10 09:26:24

标签: javascript reactjs react-hooks addeventlistener

所以我有一个屏幕组件,它可以根据类别来获取一些数据,问题是,当我更改类别时,scroll事件使用的cb函数不会刷新,而是使用了旧类别。

const categoryFromParams = safePah(false,['match','params','category'],props);

const [indexs, setIndexs] = useState({
    firstIndex: 0,
    lastIndex: 9
});


const [feed, setFeed] = useState([]);
const [loading, setLoading] = useState(false)

const handleScroll = (category, test) => () => {

    test.firstIndex = test.lastIndex;
    test.lastIndex = test.lastIndex + 9;

    const { scrollTop, scrollHeight, clientHeight } = document.documentElement;

    if (clientHeight + scrollTop >= scrollHeight - 5) {

        if (!loading) {
            setLoading(true);

            getFeedCategory({
                category,
                ...test
            }).then(response => {
                const feed = safePah([], ['data'], response);
                setLoading(false);

                setFeed(prevState => [...prevState, ...feed])
            })

        }
    }
}


    useEffect(() => {
        setLoading(true);
        setFeed([]);
        getFeedCategory({ category: categoryFromParams, ...indexs }).then(response => {
            const feed = safePah([], ['data'], response);
            setLoading(false);

            setFeed(prevState => [...prevState, ...feed])
        });

        const test = {
            firstIndex: 9,
            lastIndex: 18
        }

        window.addEventListener('scroll', debounce(handleScroll(categoryFromParams, test), 1000))

        return () => window.removeEventListener('scroll',  debounce(handleScroll(categoryFromParams, test), 1000))

    }, [categoryFromParams])

idk如何更改其行为,即当类别更改时,我的eventListner刷新。

0 个答案:

没有答案