在React应用程序中使用setInterval更新状态时出现问题

I have a function called getRandomHexagram() which returns a random 6-character string that is used for props in my <hexagram string={stringstate} /> component in my I Ching divination app.

I also have a function called resettimer() which retrieves this random 6-character string multiple times and passes it to my component within a few seconds, so that while setInterval is running, the component will keep changing its appearance until clearInterval is called.

I would like to continuously update the state using resettimer() function run until it ends, and then use the new state in another function together with clearInterval.

What is strange to me is that while the if portion of the timer is running, the component continuously updates as it should. But when I try to call the final state in the } else { statement together with clearInterval, console always shows that stringstate is still "VVVVVV", or whatever was the last prop that my component used in my previous click, NOT what my component is currently using.

function App() {

const [stringstate, setStringstate] = useState("VVVVVV");

  function resettimer() {
    var timesrun = 0;
    var randomtime = Math.floor(Math.random() * 15) + 10;
    const interval = setInterval(() => {
      timesrun += 1;
      if (timesrun < randomtime) {
        thisString = getRandomHexagram();
        setStringstate(thisString);

        console.log("the current permutation is: " + thisString);
        // console and component shows this correctly.
      } else {
        clearInterval(interval);

        console.log("the final state state is: " + stringstate);
        // Call another function here using the NEW stringstate
        // But console shows that stringstate is still showing 
        // the old state of VVVVVV despite my component showing otherwise
      }
    }, 100);
  }

... ...

  return (
    <div className="App">

      <Button onClick={() => resettimer()}>
      <Hexagram string={stringstate} />

    </div>
  );
}

单击按钮并调用函数后,控制台将显示以下内容:

the current permutation is: VPPVPB
the current permutation is: VPPPVV
the current permutation is: BPBVBV
the current permutation is: VVPVPV
the current permutation is: PPBVPV
the current permutation is: PPPBBB
the current permutation is: VVPPPV
the final state state is: VVVVVV

知道为什么会这样吗?任何建议深表感谢。

评论