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

时间:2020-05-09 13:06:15

标签: javascript reactjs react-hooks setinterval clearinterval

我有一个名为getRandomHexagram()的函数,该函数返回一个随机的6个字符的字符串,该字符串用于I Ching占卜应用程序中<hexagram string={stringstate} />组件中的道具。

我还有一个名为resettimer()的函数,该函数多次检索此随机的6个字符的字符串,并在几秒钟内将其传递给我的组件,以便在setInterval运行时,组件将保持更改外观,直到调用clearInterval

我想使用resettimer()函数运行来不断更新状态,直到结束为止,然后再与clearInterval一起在另一个函数中使用新状态。

令我感到奇怪的是,计时器的if部分正在运行时,该组件会根据需要不断更新。但是,当我尝试在} else {语句中与clearInterval一起调用最终状态时,控制台始终显示stringstate仍为"VVVVVV",或者说我上次点击中使用的组件,而不是我的当前组件。

function getRandomHexagram() {
  const flipcoins = () => {
    return (
      (Math.floor(Math.random() * 2) + 2) +
      (Math.floor(Math.random() * 2) + 2) +
      (Math.floor(Math.random() * 2) + 2)
    );
  };
  const drawline = (coinvalue) => {
    let line;
    if (coinvalue == 6) {line = "B";}
    if (coinvalue == 7) {line = "V";}
    if (coinvalue == 8) {line = "P";}
    if (coinvalue == 9) {line = "W";}
    return line;
  };
  return (
    drawline(flipcoins()) +
    drawline(flipcoins()) +
    drawline(flipcoins()) +
    drawline(flipcoins()) +
    drawline(flipcoins()) +
    drawline(flipcoins())
  );
}

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

知道为什么会这样吗?任何建议都非常感谢。

0 个答案:

没有答案