持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第29天,点击查看活动详情
今天开始一起学习分享 ahooks 的源码
ahooks是阿里巴巴出品的一套高质量可靠的 React Hooks 库
今天分享 第24个 hooks-useInterval
useInterval
useInterval 的作用是什么
useInterval 的作用是 一个可以处理 setInterval 的 Hook。
接下来 看下 API
API
useInterval(
fn: () => void,
delay?: number | undefined,
options?: Options
): fn: () => void;
Params
一共有3个参数
第1个参数是fn,表示要定时调用的函数
第2个是delay,表示间隔时间,当设置值为 undefined
时会停止计时器
第3个是options,表示配置计时器的行为
参数 | 说明 | 类型 |
---|---|---|
fn | 要定时调用的函数 | () => void |
delay | 间隔时间,当设置值为 undefined 时会停止计时器 | number | undefined |
options | 配置计时器的行为 | Options |
Options
一共有1个可配置的项
第1个是immediate,表示是否在首次渲染时立即执
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
immediate | 是否在首次渲染时立即执行 | boolean | false |
Result
参数 | 说明 | 类型 |
---|---|---|
clearInterval | 清除定时器 | () => void |
接下来 看下 用法
基础用法
每1000ms,执行一次
import React, { useState } from 'react';
import { useInterval } from 'ahooks';
export default () => {
const [count, setCount] = useState(0);
useInterval(() => {
setCount(count + 1);
}, 1000);
return <div>count: {count}</div>;
};
当输入值的时候不会立即更新,而是增加了节流,会在指定时间内才会更新
进阶使用
动态修改 delay 以实现定时器间隔变化与暂停。
import React, { useState } from 'react';
import { useInterval } from 'ahooks';
export default () => {
const [count, setCount] = useState(0);
const [interval, setInterval] = useState<number | undefined>(1000);
const clear = useInterval(() => {
setCount(count + 1);
}, interval);
return (
<div>
<p> count: {count} </p>
<p style={{ marginTop: 16 }}> interval: {interval} </p>
<button
onClick={() => setInterval((t) => (!!t ? t + 1000 : 1000))}
style={{ marginRight: 8 }}
>
interval + 1000
</button>
<button
style={{ marginRight: 8 }}
onClick={() => {
setInterval(1000);
}}
>
reset interval
</button>
<button onClick={clear}>clear</button>
</div>
);
};
接下来一起看下 源码
源码
1.首先定义传入参数的类型
fn: () => void,
delay: number | undefined,
options: {
immediate?: boolean;
} = {},
2.使用useRef定义一个定时器
const timerRef = useRef<NodeJS.Timer | null>(null);
3.返回清除定时器的函数,在useCallback中判断是否存在定时器,如果存在定时器,则使用clearInterval清除定时器
const clear = useCallback(() => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
}, []);
return clear;
4.使用useLatest包裹传入的函数。判断delay是否存在和小于零,是的话则直接return.如果immediate为true,则直接执行函数。否则的话,在指定时间执行该函数,并清除定时器
const fnRef = useLatest(fn);