在React-native中实现一个自定义倒计时Hooks

使用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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值