如何在 React 中显示倒数计时器



如何以分钟和秒为单位显示倒数计时器。 现在我能够以秒为单位显示计时器,但我想同时显示分钟和秒。

目前我的倒数计时器以这种方式显示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>
);
}

以下是格式化时间的完整解决方案:

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

关于原始代码的一些注意事项:

  1. 由于计数器的下一个值取决于前一个值,因此最好使用setState的功能形式。
  2. 最好
  3. 在组件卸载时清除超时。

从导入阶段导入钩子:

钩子反应

import React, { useState, useEffect } from "react"; 

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

setCounter方法更改为以下方法应该有效。

React.useEffect(() => {
counter !== 'Time Over' && setTimeout(() => setCounter(counter > 1 ? counter - 1 : 'Time Over'), 1000);
}, [counter]);

这可以像这样完成:

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

相关内容

  • 没有找到相关文章

最新更新