自定义 Hook 示例:useTimestampParser
下面是一个计算距目标时间戳倒计时(HH:MM:SS)的自定义 React Hook:
import { useState, useEffect } from 'react'
function useTimestampParser(timestamp) {
const [timeStr, setTimeStr] = useState(() => {
const now = Date.now()
const difference = timestamp - now
if (difference <= 0) {
return '0:0:0'
}
const hours = Math.floor(difference / (1000 * 60 * 60))
const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60))
const seconds = Math.floor((difference % (1000 * 60)) / 1000)
return `${hours}:${minutes}:${seconds}`
})
useEffect(() => {
const timer = setInterval(() => {
const now = Date.now()
const difference = timestamp - now
if (difference <= 0) {
setTimeStr('0:0:0')
} else {
const hours = Math.floor(difference / (1000 * 60 * 60))
const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60))
const seconds = Math.floor((difference % (1000 * 60)) / 1000)
setTimeStr(`${hours}:${minutes}:${seconds}`)
}
}, 1000)
return () => clearInterval(timer)
}, [timestamp])
return timeStr
}
来源整理自:vue3js.cn 面试官系列



