如果我想引用回调,useRef 的类型是什么?

What is the type of useRef if I want to referenciate a callback?

我正在关注 Dan Abramov's approach to creating a custom hook for a basic setInterval use case。但是,我很难用打字稿输入它。特别是,useRef 的类型应该是什么?这是 js 中的代码,如果可能的话,希望转录为 typescript

import React, { useState, useEffect, useRef } from 'react';

function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

在我的代码中,我会这样使用它:

export interface DataProps<Type> {
  results: Type[];
  isLoading: boolean;
  LIMIT: number;
  offset: number;
}

export interface Pokemon {
  name: string;
  url: string;
}

const [data, setData] = useState<DataProps<Pokemon>>({
    results: [],
    isLoading: true,
    LIMIT: 20,
    offset: 0
  });

useInterval(
    async () => {
      try {
        const res = await fetch(
          `https://pokeapi.co/api/v2/pokemon?` +
            new URLSearchParams({
              limit: data.LIMIT + "",
              offset: data.offset + ""
            })
        );
        const { results } = await res.json();

        setData((prevValue) => ({
          ...prevValue,
          results: [...prevValue.results, ...results],
          isLoading: false,
          offset: prevValue.offset + prevValue.LIMIT
        }));
      } catch (err) {
        console.log("Fetch Error:", err);
      }
    },
    10000
  );

您将 useRef 键入您的回调类型:

const savedCallback = useRef<typeof callback>();

如果你问的是你的回调类型应该是什么,那将取决于你想要的函数形状。最常见的是 () => Promise<void> | void 用于异步或同步函数,或 (...args: any) => Promise<void> | void 用于带参数的函数。