简体   繁体   English

使用标志 React 切换按钮

[英]Toggle button using a flag React

When a button is pressed, it calls the toggleTimer() function. Now, when I press this button, it pauses immediately , however when I press the button a second time, it does not unpause immediately.当按下一个按钮时,它会调用toggleTimer() function。现在,当我按下这个按钮时,它会立即暂停,但是当我第二次按下按钮时,它不会立即取消暂停 The goal is to get the button to toggle between these 2 states immediately after being pressed.目标是让按钮在按下后立即在这两种状态之间切换。

When I run the program I notice weirdly that I have to press my button many times before I get the unpause behaviour to work.当我运行该程序时,我奇怪地注意到我必须多次按下按钮才能使取消暂停行为起作用。 I think this is due to the let paused=true global variable, but I'm unsure how to solve this.我认为这是由于let paused=true全局变量,但我不确定如何解决这个问题。

///////PAUSE TIMER/////////////////
  let paused = true;
  let holdValue;

  function toggleTimer(){
    if (paused===true){ // if paused, we clear timer and save value
      paused = false; 
      holdValue= remainingTime;
      clearInterval(timerRef.current);
    } else if (paused===false) { //if not paused, we can restart timer using our saved value
      paused = true; 
      startTimer(); // call our function to start timer
      setRemainingTime(holdValue); // update the remaining time using our saved value
    }
  }

I believe you are right about the global var making the behaviour weird.我相信您对全局变量使行为变得奇怪的看法是正确的。

So solution is to use a state in your button component:所以解决方案是在按钮组件中使用 state:

const [paused, setPaused] = useState(false)

Then you should combine it with a useEffect that will handle the timer (I'm not sure I understood correctly but you should be able to adapt it to your need):然后你应该将它与将处理计时器的 useEffect 结合起来(我不确定我是否理解正确但你应该能够根据你的需要调整它):

const Example = () => {
  const [paused, setPaused] = useState(false);

  useEffect(() => {
    let timer;
    if (!paused) {
      timer = setInterval(() => {
        // Do something
      }, 10000);
    } else {
      clearInterval(timer);
    }

    return () => clearInterval(timer);
  }, [paused]);

  return <Button onClick={() => setPaused(!paused)}>Button</Button>;
};

Here when paused is false, the timer (interval) will call execute its callback (// Do something) every 10s, then when you click on the button paused change to false so the useEffect is executed and the time it clear the timer.这里,当paused为 false 时,计时器(间隔)将每 10 秒调用执行其回调(// Do something),然后当您单击按钮时 paused 更改为 false,以便执行 useEffect 并清除计时器的时间。 If you want to start it again, then click and the button, that will change the paused state and the useEffect will restart the interval.如果你想再次启动它,然后单击 按钮,这将更改暂停的 state 并且 useEffect 将重新启动间隔。

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

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