将这段代码中的ts语法去掉import { useEffect, useState } from 'react'; import moment from 'moment'; export interface ICountdown { deadline: string; format?: 'YYYY-MM-DD HH:mm:ss' | string; } export type Remains = Record<'day' | 'hour' | 'minute' | 'second', number>; const useCountdown = ({ deadline, format = 'YYYY-MM-DD HH:mm:ss', }: ICountdown): Remains => { const [{ current, updater }, setCurrent] = useState({ current: moment(), updater: 0, }); const [remains, setRemains] = useState<Remains>({ day: 0, hour: 0, minute: 0, second: 0, }); useEffect(() => { const timer = window.setInterval(() => { current.isSameOrAfter(moment(deadline, format)) ? clearInterval(timer) : setCurrent(prev => ({ current: prev.current.add(1, 's'), updater: prev.updater + 1, })); }, 1000); return () => clearInterval(timer); }, [deadline]); useEffect(() => { let millisec = moment(deadline, format).valueOf() - current.valueOf(); millisec = millisec >= 0 ? millisec : 0; setRemains({ day: Math.floor(millisec / (1000 * 60 * 60 * 24)), hour: Math.floor((millisec / (1000 * 60 * 60)) % 24), minute: Math.floor((millisec / (1000 * 60)) % 60), second: Math.round((millisec / 1000) % 60), }); }, [updater]); return remains; }; export default useCountdown;
时间: 2024-04-11 07:32:32 浏览: 127
babel-plugin-import-react:一个小的babel插件,可以自动导入React,它钩在您的组件上
去掉ts语法后的代码如下:
import React, { useEffect, useState } from 'react';
import moment from 'moment';
const useCountdown = ({
deadline,
format = 'YYYY-MM-DD HH:mm:ss',
}) => {
const [current, setCurrent] = useState(moment());
const [updater, setUpdater] = useState(0);
const [remains, setRemains] = useState({
day: 0,
hour: 0,
minute: 0,
second: 0,
});
useEffect(() => {
const timer = window.setInterval(() => {
const newCurrent = current.add(1, 's');
if (newCurrent.isSameOrAfter(moment(deadline, format))) {
clearInterval(timer);
} else {
setCurrent(newCurrent);
setUpdater(prev => prev + 1);
}
}, 1000);
return () => clearInterval(timer);
}, [deadline]);
useEffect(() => {
let millisec = moment(deadline, format).valueOf() - current.valueOf();
millisec = millisec >= 0 ? millisec : 0;
setRemains({
day: Math.floor(millisec / (1000 * 60 * 60 * 24)),
hour: Math.floor((millisec / (1000 * 60 * 60)) % 24),
minute: Math.floor((millisec / (1000 * 60)) % 60),
second: Math.round((millisec / 1000) % 60),
});
}, [updater]);
return remains;
};
export default useCountdown;
阅读全文