如何以分钟和秒为单位显示倒数计时器。现在,我只能以秒为单位显示计时器,但是我想同时显示分钟和秒。
当前我的倒数计时器以这种方式显示Countdown: 112
,但我希望它像Countdown: 1: 52
import React from "react";
export default function App() {
const [counter, setCounter] = React.useState(120);
React.useEffect(() => {
counter > 0 && setTimeout(() => setCounter(counter - 1), 1000);
}, [counter]);
return (
<div className="App">
<div>Countdown: {counter === 0 ? "Time over" : counter}</div>
</div>
);
}
答案 0 :(得分:1)
这是格式化时间的完整解决方案:
// Prepend `0` for one digit numbers. For that the number has to be
// converted to string, as numbers don't have length method
const padTime = time => {
return String(time).length === 1 ? `0${time}` : `${time}`;
};
const format = time => {
// Convert seconds into minutes and take the whole part
const minutes = Math.floor(time / 60);
// Get the seconds left after converting minutes
const seconds = time % 60;
//Return combined values as string in format mm:ss
return `${minutes}:${padTime(seconds)}`;
};
export default function App() {
const [counter, setCounter] = React.useState(120);
React.useEffect(() => {
let timer;
if (counter > 0) {
timer = setTimeout(() => setCounter(c => c - 1), 1000);
}
return () => {
if (timer) {
clearTimeout(timer);
}
};
}, [counter]);
return (
<div className="App">
{counter === 0 ? "Time over" : <div>Countdown: {format(counter)}</div>}
</div>
);
}
关于原始代码的一些注意事项:
setState
的功能形式。答案 1 :(得分:0)
将您的setCounter
方法更改为关注方法即可。
React.useEffect(() => {
counter !== 'Time Over' && setTimeout(() => setCounter(counter > 1 ? counter - 1 : 'Time Over'), 1000);
}, [counter]);
答案 2 :(得分:0)
可以这样做:
import React from "react";
export default function App() {
const [counter, setCounter] = React.useState(120);
React.useEffect(() => {
counter > 0 && setTimeout(() => setCounter(counter - 1), 1000);
}, [counter]);
return (
<div className="App">
<div>Countdown: {counter === 0 ? "Time over" : counter}</div>
</div>
);
}
答案 3 :(得分:0)
从导入阶段导入钩子:
import React,
{useState,useEffect}
来自“反应”;
export default function App() {
const [counter, setCounter] = useState(120);
useEffect(() => {
counter > 0 && setTimeout(() => setCounter(counter - 1), 1000);
}, [counter]);
return (
<div className="App">
<div>Countdown: {counter === 0 ? "Time over" : counter}</div>
</div>
);
}