本文介绍了在数组中带有参数的useState会破坏setInterval,并使其不稳定和不稳定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚才在这里问了一个问题:react value of a state variable different in a different function

现在我有了新问题。

具有如下所示的使用效果

  useEffect(() => {
    countDown();
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);

正在中断如下所示的setInterval:

  const countDown = () => {
    // let strokeCountdown = Math.floor(Math.random() * 31) + 100;
    let strokeCountdown = 20
    let strokeCountdownSpeedOptions = [1000, 500, 300, 200];
    let strokeCountDownSpeed = strokeCountdownSpeedOptions[Math.floor(Math.random()*strokeCountdownSpeedOptions.length)];
    let strokeCounter = setInterval(() => {
        strokeCountdown--
        setStrokeCountdown(strokeCountdown)
        if (strokeCountdown === 0) {
            endOfGameRound()
            clearInterval(strokeCounter)
            setTotalStrokeScore(strokeScore);
        }
    }, strokeCountDownSpeed)
  }

完整组件如下所示:

import React, { useEffect, useState } from 'react';

function ScoreCard() {

  const [strokeScore, setStrokeScore] = useState(1);

  const [totalStrokeScore, setTotalStrokeScore] = useState(1);

  const [strokeCountdown, setStrokeCountdown] = useState();

  const strokeCountdownDing = new Audio('/sounds/round-complete.mp3');

  // make new variable, maybe? 
  let strokeScoreCount = 0;

  const endOfGameRound = () => {
    strokeCountdownDing.play();
    document.getElementById('stroke-counter-button').disabled = true;
  }

  const addToStrokeScore = () => {
    setStrokeScore(prev => prev + 1);
    // prints the correct number
    console.log('Score in function', strokeScore);
    if (strokeCountdown === 0) {
        endOfGameRound()
    }
  }

  const subtractStrokeScore = () => {
    setStrokeScore(strokeScore - 1);
  }

  const countDown = () => {
    // let strokeCountdown = Math.floor(Math.random() * 31) + 100;
    let strokeCountdown = 20
    let strokeCountdownSpeedOptions = [1000, 500, 300, 200];
    let strokeCountDownSpeed = strokeCountdownSpeedOptions[Math.floor(Math.random()*strokeCountdownSpeedOptions.length)];
    let strokeCounter = setInterval(() => {
        strokeCountdown--
        setStrokeCountdown(strokeCountdown)
        if (strokeCountdown === 0) {
            endOfGameRound()
            clearInterval(strokeCounter)
            setTotalStrokeScore(strokeScore);
        }
    }, strokeCountDownSpeed)
  }

  useEffect(() => {
    countDown();
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);

  return (
    <div className="game__score-card">
      <div className="game__speed-level">
          Speed: idk
      </div>
      <div className="game__stroke-countdown">
          Countdown: {strokeCountdown}
      </div>
      <p>Score: {strokeScore}</p>
      <button id="stroke-counter-button" onClick={addToStrokeScore}>
          {strokeCountdown === 0 ? 'Game Over' : 'Stroke'}
      </button>
      {/* window.location just temp for now */}
      {strokeCountdown === 0 
        ? <button onClick={() => window.location.reload(false)}>Play Again</button>
        : <button disabled>Game in Progress</button>
      }
      <div className="game__total-score">
          Total score: {totalStrokeScore}
      </div>
    </div>
  );
}

export default ScoreCard;

当我单击该按钮时,计时器变得不稳定,并且到处都是。

我想做的就是让计时器平稳地倒计时,获取用户的点击量并将其添加到总分中。

为什么

  useEffect(() => {
    countDown();
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);

打破一切?

推荐答案

我每次点击都在呼叫countDown(),所以我就这么做了

  useEffect(() => {
    if (strokeScore === 1) {
        countDown();
    }
    console.log('Score in useeffect', strokeScore);
  }, [strokeScore]);

这篇关于在数组中带有参数的useState会破坏setInterval,并使其不稳定和不稳定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 11:03