#说明

React中 可以处理 setInterval 的 Hook, 此处为ahooks的摘录

一、直接上代码

  1. import { useEffect, useRef } from 'react';
  2. function useInterval(
  3. fn: () => void,
  4. delay: number | null | undefined,
  5. options?: {
  6. immediate?: boolean;
  7. },
  8. ): void {
  9. const immediate = options?.immediate;
  10. const fnRef = useRef<() => void >();
  11. fnRef.current = fn;
  12. useEffect(() => {
  13. if (delay === undefined || delay === null) return;
  14. if (immediate) {
  15. fnRef.current?.();
  16. }
  17. const timer = setInterval(() => {
  18. fnRef.current?.();
  19. }, delay);
  20. return () => {
  21. clearInterval(timer);
  22. };
  23. }, [delay]);
  24. }
  25. export default useInterval;

二、解释

Ⅰ - useRef

  1. const refContainer = useRef(initialValue);

useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内持续存在。

一个常见的用例便是命令式地访问子组件:

  1. function TextInputWithFocusButton() {
  2. const inputEl = useRef(null);
  3. const onButtonClick = () => {
  4. // `current` 指向已挂载到 DOM 上的文本输入元素
  5. inputEl.current.focus();
  6. };
  7. return (
  8. <>
  9. <input ref={inputEl} type="text" />
  10. <button onClick={onButtonClick}>Focus the input</button>
  11. </>
  12. );
  13. }

本质上,useRef 就像是可以在其 .current 属性中保存一个可变值的“盒子”。

你应该熟悉 ref 这一种访问 DOM 的主要方式。如果你将 ref 对象以 <div ref={myRef} /> 形式传入组件,则无论该节点如何改变,React 都会将 ref 对象的 .current 属性设置为相应的 DOM 节点。

然而,useRef()ref 属性更有用。它可以很方便地保存任何可变值,其类似于在 class 中使用实例字段的方式。

这是因为它创建的是一个普通 Javascript 对象。而 useRef() 和自建一个 {current: ...} 对象的唯一区别是,useRef 会在每次渲染时返回同一个 ref 对象。

请记住,当 ref 对象内容发生变化时,useRef不会通知你。变更 .current 属性不会引发组件重新渲染。如果想要在 React 绑定或解绑 DOM 节点的 ref 时运行某些代码,则需要使用回调 ref 来实现。

三、使用

```tsx import React, { useState } from ‘react’; import { useInterval } from ‘useInterval’;

export default () => { const [count, setCount] = useState(0); const [interval, setInterval] = useState(1000);

useInterval( () => { setCount(count + 1); }, interval, { immediate: true }, );

return (

count: {count}

interval: {interval}

); }; ```