对于后台系统,上面筛选,下面表格分页的页面,这个hook非常实用
omitBy方法:过滤不为undefined的对象属性
javascript
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;
};
javascript
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];
};
使用
javascript
const [classData, loading] = useFetchHook(yourFetchFunc, { ...filterParams, ...paginationParams }, [], [filterParams, paginationParams, filterFlag]);
filterParams: 用在筛选条件
paginationParams:分页筛选
filterFlag:其他自定义筛选