React无法正确处理计数器

我有一个简单的代码,它遍历数组并以1000 ms的间隔记录它们,如下所示:

  const arr = [1, 2, 3];
  let i = 0;
  const choice = () => {
    const interval = setInterval(() => {
      console.log(arr[i++ % arr.length]);
      if (i === 8) {
        clearInterval(interval);
      }
    }, 1000);
  };

  choice();

Upon introducing React state into the code, the whole thing goes absolutely mad and starts counting out of the interval to a point that I reach almost infinite loop although the simple console.log instead of react state works fine.

  const [ele, setEle] = React.useState(null);
  const arr = [1, 2, 3];
  let i = 0;
  const choice = () => {
    const interval = setInterval(() => {
      setEle(arr[i++ % arr.length]);
      if (i === 8) {
        clearInterval(interval);
      }
    }, 1000);
  };

  choice();

return( 
    <h1>{ele}</h1>
)

我想知道如何使用当前代码的状态来达到效果。

https://codesandbox.io/s/condescending-dubinsky-kbl5m

评论
  • melissashu
    melissashu 回复

    With your current implementation, every render of the component is initializing a new interval. Use setTimeout instead, so that every render only initializes exactly one action to take place in the future.

    由于每次更改的都是数组的索引,因此请考虑设置该状态:

    export default function App() {
      const [i, setI] = React.useState(0);
      const arr = [1, 2, 3];
      if (i !== 8) {
        setTimeout(() => {
          setI(i + 1);
        }, 1000);
      }
    
      return (
        <div className="App">
          <h1>{arr[i % arr.length]}</h1>
        </div>
      );
    }