首页 > 解决方案 > 通过传递时间(作为 Api 的响应获得)作为道具在 React with Hooks 中实现倒数计时器

问题描述

我是新来的反应,我正在尝试根据从 API 响应获得的时间使用反应挂钩显示倒数计时器,但我不确定呈现它的最佳方式是什么。当我在 中传递时间时useRef,我可以在传递时间(从 API 响应中获得)的同时显示计时器,因为我无法更新状态。

我尝试了几种方法,但没有一种方法有效。请帮我解决这个问题。

const [timeLeft, setTimeLeft] = useState("05:00");

let time = useRef(props.sessionEndTime);

useEffect(() => {

    const timer = setTimeout(() => {

        if (time.current > 0) {

            if(extendTime === false){

                  time.current = (time.current - 1000);
              } else {
                 time.current=time.current +300000;
                 setExtendTime(false);
              }

            const timeObj = {

                mins: Math.floor((time.current / (1000 * 60)) % 60).toString(),

                secs: Math.floor((time.current / 1000) % 60).toString()

            }

            let displayTime = ((((timeObj.mins.length === 1) ? "0" : "") + timeObj.mins) + ":" +
            (((timeObj.secs.length === 1) ? "0" : "") + timeObj.secs))

           setTimeLeft(displayTime);
        }
    
    }, 1000); 
     return () => clearTimeout(timer);
},[timeLeft])

标签: reactjsreact-hooks

解决方案


推荐阅读