简体   繁体   English

Y 滚动事件监听器 useEffect

[英]Y scroll event listener useEffect

My code underneath is a simple React component that sets a new state upon scrolling the page down.我下面的代码是一个简单的 React 组件,它在向下滚动页面时设置一个新的 state。 If the Y scroll exceeds a certain position it will set another state to true.如果 Y 滚动超过某个 position 它将设置另一个 state 为真。

    const [ scrollPosition, setScrollPosition ] = useState(0);
    const [ confetti, setConfetti ] = useState(false);

    useEffect(
        () => {
            window.addEventListener('scroll', handleScroll, { passive: true });
            check();

            return () => {
                window.removeEventListener('scroll', handleScroll);
            };
        },
        [ scrollPosition ]
    );
    const handleScroll = () => {
        const position = window.pageYOffset;
        setScrollPosition(position);
    };
    
    const check = () => {
        if (scrollPosition > 400) {
            setConfetti(true);
        }
        if (scrollPosition < 401) {
            setConfetti(false);
        }
    };

Everything is working smoothly as expected but I was just wondering if there is a less expensive way of doing this.一切都按预期顺利进行,但我只是想知道是否有更便宜的方法可以做到这一点。 Re-rendering the page every time Y scroll changes seems like a very inefficient way to run this code.每次 Y 滚动更改时重新渲染页面似乎是运行此代码的一种非常低效的方式。 I don't think throttling would be a good idea either as there might be a delay when a user scrolls down really fast.我认为节流也不是一个好主意,因为当用户快速向下滚动时可能会有延迟。 Thanks to anyone who can help!感谢任何能提供帮助的人!

You don't need to save the scroll position in the state.您不需要将卷轴 position 保存在 state 中。

useEffect(() => {
    window.addEventListener("scroll", handleScroll, { passive: true });

    return () => {
        window.removeEventListener("scroll", handleScroll);
    };
}, [scrollPosition]);
const handleScroll = () => {
    const position = window.pageYOffset;
    if (position > 400) {
        setConfetti(true);
    }
    if (position < 401) {
        setConfetti(false);
    }
};

In useEffect Hook, the value pass in last array depends the call the render method.在 useEffect Hook 中,最后一个数组中传递的值取决于调用 render 方法。 Whenever value in array change useEffect call and subsequently render method invoke.每当数组中的值更改 useEffect 调用并随后调用渲染方法时。 Better you remove array value.最好删除数组值。

 useEffect(
    () => {
        window.addEventListener('scroll', handleScroll, { passive: true });
        check();

        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    },
    []
);

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

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