reacthooks实现取当前时刻分钟为5或5的倍数实现5分钟粒度每秒倒计时
时间: 2023-11-27 19:54:22 浏览: 132
可以使用`useEffect`和`useState`来实现这个功能。具体实现步骤如下:
1. 使用`useState`来保存当前时刻的分钟数和计算出距离下一个5分钟的秒数。
```jsx
const [currentMinute, setCurrentMinute] = useState(new Date().getMinutes());
const [secondsToNextFive, setSecondsToNextFive] = useState(
(5 - (currentMinute % 5)) * 60 - new Date().getSeconds()
);
```
2. 使用`useEffect`来更新状态值,每秒钟计算一次距离下一个5分钟的秒数。
```jsx
useEffect(() => {
const intervalId = setInterval(() => {
const currentMinute = new Date().getMinutes();
setCurrentMinute(currentMinute);
setSecondsToNextFive(
(5 - (currentMinute % 5)) * 60 - new Date().getSeconds()
);
}, 1000);
return () => clearInterval(intervalId);
}, []);
```
3. 使用`Math.floor`函数来计算倒计时的分钟数和秒数,并且使用条件渲染来判断是否需要显示倒计时。
```jsx
const minutesLeft = Math.floor(secondsToNextFive / 60);
const secondsLeft = secondsToNextFive % 60;
return (
<div>
{minutesLeft === 0 && secondsLeft === 0 ? (
<p>It's a multiple of 5 minute!</p>
) : (
<p>
{`Next multiple of 5 minute: ${minutesLeft}m ${secondsLeft}s`}
</p>
)}
</div>
);
```
完整代码如下:
```jsx
import React, { useState, useEffect } from "react";
function Countdown() {
const [currentMinute, setCurrentMinute] = useState(new Date().getMinutes());
const [secondsToNextFive, setSecondsToNextFive] = useState(
(5 - (currentMinute % 5)) * 60 - new Date().getSeconds()
);
useEffect(() => {
const intervalId = setInterval(() => {
const currentMinute = new Date().getMinutes();
setCurrentMinute(currentMinute);
setSecondsToNextFive(
(5 - (currentMinute % 5)) * 60 - new Date().getSeconds()
);
}, 1000);
return () => clearInterval(intervalId);
}, []);
const minutesLeft = Math.floor(secondsToNextFive / 60);
const secondsLeft = secondsToNextFive % 60;
return (
<div>
{minutesLeft === 0 && secondsLeft === 0 ? (
<p>It's a multiple of 5 minute!</p>
) : (
<p>
{`Next multiple of 5 minute: ${minutesLeft}m ${secondsLeft}s`}
</p>
)}
</div>
);
}
export default Countdown;
```
阅读全文