使用 React Hooks 的倒计时器

And*_*ato 2 javascript components timer reactjs react-hooks

所以定时器起作用了。如果我this.state使用特定的倒计时数字进行硬编码,则计时器在页面加载后开始倒计时。我希望时钟在单击按钮时开始倒计时,并具有将 的 更改nullstate随机生成的数字的功能。我对 React 有点陌生。我知道useState()只设置初始值,但如果我使用点击事件,如何重置useState()?我一直在尝试使用setCountdown(ranNum),但它使我的应用程序崩溃。我确信答案是显而易见的,但我只是没有找到它。

如果我没有提供足够的代码,请告诉我。我不想发布整个shebang。

这是我的代码:

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

export const Timer = ({ranNum, timerComplete}) => {
    const [ countDown, setCountdown ] = useState(ranNum)
    useEffect(() => {
        setTimeout(() => {
            countDown - 1 < 0 ? timerComplete() : setCountdown(countDown - 1)
        }, 1000)
    }, [countDown, timerComplete])
    return ( <p >Countdown: <span>{ countDown }</span> </p> )
}


Run Code Online (Sandbox Code Playgroud)
  handleClick(){
    let newRanNum = Math.floor(Math.random() * 20);
    this.generateStateInputs(newRanNum)
    let current = this.state.currentImg;
    let next = ++current % images.length;
    this.setState({
      currentImg: next,
      ranNum: newRanNum
    })
  }

 <Timer ranNum={this.state.ranNum} timerComplete={() => this.handleComplete()} />
 <Button onClick={this.handleClick}  name='Generate Inputs' />
 <DisplayCount name='Word Count: ' count={this.state.ranNum} />

Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 6

您应该存储countDown在父组件中并将其传递给子组件。在父组件中,您应该使用一个变量来触发何时启动Timer。你可以试试这个:

import React from "react";

export default function Timer() {
  const [initialTime, setInitialTime] = React.useState(0);
  const [startTimer, setStartTimer] = React.useState(false);

  const handleOnClick = () => {
    setInitialTime(5);
    setStartTimer(true);
  };

  React.useEffect(() => {
    if (initialTime > 0) {
      setTimeout(() => {
        console.log("startTime, ", initialTime);
        setInitialTime(initialTime - 1);
      }, 1000);
    }

    if (initialTime === 0 && startTimer) {
      console.log("done");
      setStartTimer(false);
    }
  }, [initialTime, startTimer]);

  return (
    <div>
      <buttononClick={handleOnClick}>
        Start
      </button>
      <Timer initialTime={initialTime} />
    </div>
  );
}

const Timer = ({ initialTime }) => {
  return <div>CountDown: {initialTime}</div>;
};
Run Code Online (Sandbox Code Playgroud)