使用React自定义Hooks的概念,写一个倒计时Hook
处理new Date时,在IOS和Android上有兼容性问题,这里记录一下
chrome、安卓中都可以通过new Date(‘2021.12.11 00:00’)或new Date(‘2021-12-11 00:00’)转换为正常Date对象。
在IOS中,都会转换为NaN,IOS只支持new Date(‘2021/12/11 00:00’)格式。
而且IOS中不支持 24:00 点,24:00也会转换为NaN,需要写为第二天的 00:00。
所以为了兼容ios,将日期转换为 '/' 连接的:var d = new Date("2017-08-11 12:00:00".replace(/-/g, "/"))。
同时不要写24:00的时间,统一写为00:00点。
useCountDown接收一个参数(剩余时间秒数);产出:count(剩余时间秒数)、start(开始计时)、stop(结束计时)
import { useAppState } from '@react-native-community/hooks';
import { useCallback, useEffect, useRef, useState } from 'react';
export function useCountdown(seconds = 60) {
const timer = useRef(null);
const [target, setTarget] = useState(null);
const [count, setCount] = useState(seconds);
const appState = useAppState();
const start = useCallback(second => {
setTarget(add(new Date(), second || seconds));
}, [seconds]);
const stop = useCallback(() => {
setTarget(null);
}, []);
useEffect(() => {
if (target === null || appState !== 'active') {
return null;
}
setCount(diff(new Date(), target));
timer.current = setInterval(() => {
setCount(diff(new Date(), target));
}, 1000);
return () => {
if (timer.current) {
clearInterval(timer.current);
timer.current = null;
}
};
}, [target, appState]);
useEffect(() => {
if (count === 0) {
stop();
}
}, [count, stop]);
return { count, start, stop };
}
function add(date, seconds) {
return new Date(date.getTime() + seconds * 1000);
}
function diff(now, target) {
return Math.max(Math.trunc((target.getTime() - now.getTime()) / 1000 + 0.5), 0);
}