Countdown timer in React

后端 未结 7 814
甜味超标
甜味超标 2020-11-30 00:05

I have seen lots of countdown timers in JavaScript and wanted to get one working in React.

I have borrowed this function I found online:

secondsToTim         


        
7条回答
  •  攒了一身酷
    2020-11-30 00:44

    Here is a solution using hooks, Timer component, I'm replicating same logic above with hooks

    import React from 'react'
    import { useState, useEffect } from 'react';
    
    const Timer = (props:any) => {
        const {initialMinute = 0,initialSeconds = 0} = props;
        const [ minutes, setMinutes ] = useState(initialMinute);
        const [seconds, setSeconds ] =  useState(initialSeconds);
        useEffect(()=>{
        let myInterval = setInterval(() => {
                if (seconds > 0) {
                    setSeconds(seconds - 1);
                }
                if (seconds === 0) {
                    if (minutes === 0) {
                        clearInterval(myInterval)
                    } else {
                        setMinutes(minutes - 1);
                        setSeconds(59);
                    }
                } 
            }, 1000)
            return ()=> {
                clearInterval(myInterval);
              };
        });
    
        return (
            
    { minutes === 0 && seconds === 0 ? null :

    {minutes}:{seconds < 10 ? `0${seconds}` : seconds}

    }
    ) } export default Timer;

提交回复
热议问题