使用React Hooks的倒数计时器 [英] Countdown timer using React Hooks

查看:103
本文介绍了使用React Hooks的倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此计时器正常工作.如果我用特定的倒计时编号对 this.state 进行硬编码,则一旦页面加载,计时器就会开始倒计时.我希望时钟在单击按钮时开始倒计时,并具有将 state null 更改为随机生成的数字的功能.我对React有点陌生.我知道 useState()仅设置初始值,但是如果我使用click事件,如何重置 useState()?我一直在尝试使用 setCountdown(ranNum),但是它使我的应用程序崩溃.我相信答案是显而易见的,但我找不到.

So the timer works. If I hard code this.state with a specific countdown number, the timer begins counting down once the page loads. I want the clock to start counting down on a button click and have a function which changes the null of the state to a randomly generated number. I am a bit new to React. I am know that useState() only sets the initial value but if I am using a click event, how do I reset useState()? I have been trying to use setCountdown(ranNum) but it crashes my app. I am sure the answer is obvious but I am just not finding it.

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

If I didnt provide enough code, please let me know. I didn't want to post the whole 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> )
}


  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} />

推荐答案

您应将 countDown 存储在父组件中,并将其传递给子组件.在父组件中,应该使用变量触发何时启动 Timer .您可以尝试以下方法:

You should store countDown in the parent component and pass it to the child component. In the parent component, you should use a variable to trigger when to start Timer. You can try this:

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>;
};

这篇关于使用React Hooks的倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆