import useConutDonw from './useCountDown';
function App() {
const countDown = useCountDown(1648836799000);
const [[monthes, days, hours, minutes, seconds], setCountDown] = React.useState([0, 0, 0, 0, 0])l
React.useEffect(() => {
setCountDown(countDown);
}, [countDown])
return (
<div>
{
`${monthes}个月${days}天 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}
</div>
)
}
function useCountDown (timeStamp) {
const [countDown, setCountDown] = React.useState([0, 0, 0, 0, 0]);
let t = null;
function doCountDown () {
const nowTimeStamp = new Date().getTime(),
diffTimeStamp = timeStamp - nowTimeStamp,
diffDate = new Date(diffTimeStamp),
diffMonths = diffDate.getMonth(),
diffDays = diffDate.getDate(),
diffHours = diffDate.getHours(),
diffMinutes = diffDate.getMinutes(),
diffSeconds = diffDate.getSeconds();
setCountDown([
diffMonths,
diffDays,
diffHours,
diffMinutes,
diffSeconds,
]);
if (diffMonths === 0 && diffDays === 0 && diffHours === 0 && diffMinutes === 0 && diffSeconds === 0) {
clearInterval(t);
t = null;
return;
}
React.useEffect({} => {
t = setInterval(doCountDown, 1000);
}, []);
return countDown;
}
}
export default useCountDown;