reactjs - 通过传递时间(作为 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])
解决方案
推荐阅读
- r - 如何测试向量中的每个值是否与字符串向量中的任何值匹配?
- nullpointerexception - 无法识别 NullPointerException 的来源
- java - Java a.add(b) 方法
- python - 使用 Tatsu / grako 使用无大小写关键字解析代码
- ios - UIAlert 无法将类型“(_) throws -> ()”的值转换为预期的参数类型“((UIAlertAction) -> Void)?”
- python - 在神经网络中实现用户输入
- reactjs - 如何设置参数 react router 不误会与静态路由器?
- java - String.trim() 比 String.replace() 快吗?
- android - 如何在使用 Espresso 的仪器测试中注入 Mocked Presenter of Activity
- javascript - Ruby on Rails Partial 不会使用 AJAX 刷新,但会在控制台中渲染部分