如何在react-Hooks中重置计时器

问题描述 投票:0回答:1

我试图迫使效果重新运行,以便在React-hooks中再次开始间隔

这里是沙箱https://codesandbox.io/s/dreamy-villani-8z938?file=/src/App.js中的完整代码

const [timerReset, resetTimer] = React.useReducer(x => x + 1, 0);

Reducer函数x => x + 1每当调用分派时都会递增timerReset值。然后,我使用timerReset强制重新运行效果,以便再次开始间隔(如果已停止)]

我的时间码是

import React from "react";
import "./styles.css";

export default function Timer({
  estimatedTime,
  onTick,
  active,
  newTime,
  timerReset
}) {
  const [counter, setCounter] = React.useState(estimatedTime);
  const [counterSecond, setCounterSecond] = React.useState(newTime);

  React.useEffect(() => {
    let timer;
    let timersecond;
    if (active) {
      timersecond = setTimeout(() => setCounterSecond(counterSecond + 1), 1000);
      timer = counter > 0 && setTimeout(() => setCounter(counter - 1), 1000);
    } else {
      onTick(counterSecond);
    }
    return () => {
      if (timer && timersecond) {
        clearTimeout(timer);
        clearTimeout(timersecond);
      }
    };
  }, [counter, counterSecond, active, onTick, timerReset]);

  return (
    <div>
      <div>Time: {counterSecond} </div>
      <div>Countdown: {counter}</div>
    </div>
  );
}```



reactjs
1个回答
0
投票

[timerReset应该是boolean,并且应该在Timer中使用它:

  // App
  const [timerReset, resetTimer] = React.useReducer(p => !p, false);

  // Timer
  React.useEffect(() => {
    if (timerReset) {
      setCounterSecond(newTime);
      setCounter(estimatedTime);
    }
  }, [timerReset, newTime, estimatedTime]);

Edit quizzical-leaf-i30b3

© www.soinside.com 2019 - 2024. All rights reserved.