简体   繁体   English

如何在反应中使用 setInterval?

[英]How to use setInterval in react?

I'm trying to make a simple setInterval function for a typing game but it keeps glitching out depending on my syntax or not updating at all as it is now.我正在尝试为打字游戏制作一个简单的 setInterval 函数,但它根据我的语法不断出现故障,或者根本没有像现在这样更新。

How do I get this to update every second and call the functions in the if statement?我如何让它每秒更新并调用 if 语句中的函数?

const [counter, setCounter] = useState(10);

useEffect(() => {
  let timer = setInterval(() => {
    setCounter(counter - 1);

    if (counter === 0) {
      setWordIndex(wordIndex + 1);
      setLives(lives - 1);
      life.play();
      setCounter(10);
    }
  }, 1000);
}, []);

*********Edit*************** *********编辑***************

This is what I have now that is working.这就是我现在正在工作的东西。 The first answer fixed the async issue of the counter not decrementing but I had to move the if statement outside of the useEffect to correct what I believe was caused by this same problem.第一个答案解决了计数器不递减的异步问题,但我不得不将 if 语句移到 useEffect 之外以纠正我认为是由同一问题引起的。

 useEffect(() => {
    let timer = setInterval(() => {
      setCounter( counter => counter - 1);
    }, 1000);
  }, []);
  if (counter == 0) {
    setWordIndex(wordIndex + 1);
    setLives(lives - 1);
    life.play();
    setCounter(10);
  }

Use callback function in setCounter function.setCounter函数中使用回调函数。 As you are calling the state update in an async function.当您在异步函数中调用状态更新时。 it's good practice to update the state based on the previous state.根据先前的状态更新状态是一种很好的做法。

const [counter, setCounter] = useState(10);
useEffect(() => {
    let timer = setInterval(() => {
        setCounter(counter => {
            const updatedCounter = counter - 1;
            if (updatedCounter === 0) {
                setWordIndex(wordIndex + 1);
                setLives(lives - 1);
                life.play();
                return 10;
            }
            return updatedCounter;
        }); // use callback function to set the state

    }, 1000);
    return () => clearInterval(timer); // cleanup the timer
}, []);

The previous answers aren't considering the counter values aren't immediately updating.以前的答案没有考虑计数器值不会立即更新。 They are also prone memory leaks since setInterval isn't cleared.由于未清除 setInterval,它们也容易发生内存泄漏。

const [counter, setCounter] = useState(10);
useEffect(() => {
  let timer = setInterval(() => {
    setCounter( counter => {
        const nC = counter - 1;
        if (nC === 0) {
           setWordIndex(wordIndex + 1);
           setLives(lives - 1);
           life.play();
           return 10;
        }
        return nC;
     });
  }, 1000);
  return () => clearInterval(timer);
}, []);

The previous answers weren't considering other states - wordIndex and lives and didn't include clear Intervals之前的答案没有考虑其他状态 - wordIndex 和 life 并且没有包含明确的 Intervals

It's advisable to use callback setState inside setIntervals and clear the interval on next useEffect call建议在 setIntervals 中使用回调 setState 并清除下一次 useEffect 调用的间隔

  const [counter, setCounter] = React.useState(10);
  React.useEffect(() => {
    let timer = setInterval(() => {
      // It's advisable to use callback setState inside setIntervals
      setCounter(prev => {
        if (prev !== 0) return prev - 1;

        setWordIndex(wordIndex + 1);
        setLives(lives - 1);
        life.play();    
        return 10;
      });
    }, 1000);

    // And clear the interval next useEffect call
    return () => clearInterval(timer);
  }, [wordIndex, lives]);

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

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