自学内容网 自学内容网

封装一个请求的hook(react函数组件)

对于后台系统,上面筛选,下面表格分页的页面,这个hook非常实用
omitBy方法:过滤不为undefined的对象属性

export const omitBy = <T extends IObject, K extends keyof T>(object:T, predicate:(value:T[K]) => boolean):IObject => {
  if (typeof object !== 'object') {
    return object;
  }
  const newObject:IObject = {};

  Object.keys(object).forEach((item) => {
    if (predicate(object[item])) {
      newObject[item] = object[item];
    }
  });
  return newObject;
};
export const useFetchHook = (fetchPromiseFunc:(params?:any) => Promise<any>, params?:any, initialData?:any, deps?:ReadonlyArray<any>, fetchFlag?:boolean) => {
  const [data, setData] = useState(initialData);
  const [loading, setLoading] = useState(false);
  console.log('重新执行了该hook');

  // 处理对象参数:当value为空时,omit该参数
  const formattedParams = omitBy(params, (item) => item !== undefined );
  useEffect(() => {
    const fetchData = async() => {
      try {
        setLoading && setLoading(true);
        const result = await fetchPromiseFunc(formattedParams);
        if (result.status.toString() !== '200') {
          if(result.data.error_code) {
            //todo sth...
          } else if(result.data.statusText){
            message.error(result.data.statusText);
          } else if(result.data.msg) {
            message.error(result.data.msg || '接口异常');
          }
        } else {
          setData(result.data);
        }
        setLoading && setLoading(false);
      } catch (error) {
        setLoading && setLoading(false);
      }
    };
    if(fetchFlag === undefined || fetchFlag) {
      fetchData();
    }else {
      setData(initialData);
    }
  }, deps ? deps : []);
  return [data, loading];
};

使用

const [classData, loading] = useFetchHook(yourFetchFunc, { ...filterParams, ...paginationParams }, [], [filterParams, paginationParams, filterFlag]);

filterParams: 用在筛选条件
paginationParams:分页筛选
filterFlag:其他自定义筛选


原文地址:https://blog.csdn.net/lwl12345678_/article/details/143433777

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!