简体   繁体   English

setTimeout 在 useEffect 挂钩

[英]setTimeout in useEffect hook

I am attempting to make it so that a different page from an array is displayed every 5 seconds.我正在尝试使其每 5 秒显示一次来自数组的不同页面。 I currently have it working, except the page isn't always switching every 5 seconds, but sometimes 10 or 15 seconds.我目前有它的工作,除了页面并不总是每 5 秒切换一次,但有时是 10 或 15 秒。 I believe this to be because I am not clearing the timeout correctly, any suggestions?我相信这是因为我没有正确清除超时,有什么建议吗?

const pages = [
    'screen1', 'screen2'
];

const [displayedPage, setDisplayedPage] = useState(pages[0]);
const [count, setCount] = useState(0);

   useEffect(() => {
    const timer: ReturnType<typeof setTimeout> = setTimeout(() => {
        const randomNumber = pages[Math.floor(Math.random() * pages.length)];

        if (randomNumber === displayedPage) {
            setCount(count + 1);
            clearTimeout(timer);
            return timer;
        }
        setDisplayedPage(randomNumber);
    }, 5000);

    return () => clearTimeout(timer);

});

To make everlasting cycles you should use setInterval, to avoid problems with rerenders you can useRef要制作永久循环,您应该使用 setInterval,以避免出现重新渲染问题,您可以使用 Ref

const pages = [ 'screen1', 'screen2' ];

const [displayedPage, setDisplayedPage] = useState(0);
const [count, setCount] = useState(0);
const timer = useRef()

useEffect(() => {
  const timer.current = setInterval(() => {
    const randomNumber = Math.floor(Math.random() * pages.length);
    setCount(count + 1);
    setDisplayedPage(current => 
      randomNumber == current ? 
        pages[(current+1)%pages.length]
        :
        pages[randomNumber]
    );
  }, 5000);
  return () => clearInterval(timer.current);
});

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

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