UNPKG

@td-design/rn-hooks

Version:

从ahooks里面抽取的一些在rn项目里可以使用的hooks。提高开发效率

51 lines (48 loc) 1.53 kB
import { __read } from '../_virtual/_tslib.js'; import { useRef, useState, useEffect } from 'react'; import useAppState from '../useAppState/index.js'; import useMemoizedFn from '../useMemoizedFn/index.js'; function useCountDown(seconds) { var appState = useAppState(); var timer = useRef(); var _a = __read(useState(null), 2), target = _a[0], setTarget = _a[1]; var _b = __read(useState(0), 2), count = _b[0], setCount = _b[1]; var start = useMemoizedFn(function () { setTarget(add(new Date(), seconds)); }); var stop = useMemoizedFn(function () { setTarget(null); setCount(0); }); useEffect(function () { if (target === null || appState !== 'active') return; setCount(diff(new Date(), target)); timer.current = setInterval(function () { setCount(diff(new Date(), target)); }, 1000); return function () { if (timer.current) { clearInterval(timer.current); timer.current = undefined; } }; }, [target]); useEffect(function () { if (count === 0) { stop(); } }, [count, stop]); return { count: count, start: start, stop: 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); } export { useCountDown as default };