1. 通過(guò)useRef,useEffect定義一個(gè)定時(shí)器hook
import { useRef, useEffect } from 'react';
export default function useInterval(callback, delay) {
const latestCallback = useRef(() => {});
useEffect(() => {
latestCallback.current = callback;
});
useEffect(() => {
if (delay !== null) {
const interval = setInterval(() => latestCallback.current(), delay || 0);
return () => clearInterval(interval);
}
return undefined;
}, [delay]);
}
2. 使用
import { useInterval } from 'utils'
const test = props => {
const [count, setCount] = useState(5);
useInterval(() => {
setCount(count - 1);
}, 1000);
return (
<View>
{count < 1 ? (
<Button {...resendBtn} press={() => setCount(5)} />
) : (
<Text style={{ margin: 5, color: 'gray', fontSize: 12 }}>{count}s后重新發(fā)送</Text>
)}
</View>
);
};