React自定义hooks模版代码

import React from 'react';
import { get } from '../http';

/** 获取草稿箱数量 */
export const useCount = (id: string, api = '/v1/tenant/data/draft/count') => {
  const normalizedApi = api.endsWith('/') ? api : `${api}/`;
  const [count, setCount] = React.useState(0);
  const [loading, loadingSet] = React.useState(false);
  /** 获取草稿箱数量 */
  const getCount = React.useCallback(async () => {
    if (!id) {
      return;
    }
    loadingSet(true);
    const res = await get(`${normalizedApi}${id}`);
    loadingSet(false);
    if (res.result) {
      setCount(res.data);
    }
  }, [id, normalizedApi]);

  const refresh = () => {
    getCount();
  };

  React.useEffect(() => {
    if (!id) {
      return;
    }
    getCount();
  }, [getCount, id]);

  return { count, refresh, loading };
};

发个代码块呢,图片不方便佬们复制。

react-query
swr
ahooks 里的 useRequest

了解一下

感谢大佬分享 。