- 新增 useCrudDrawer hook 封装 CRUD Drawer 通用模式(状态管理/提交/错误处理) - 新增 useListData hook 封装非分页列表数据获取 - 11 个页面统一迁移到 DrawerForm + 共享 hooks,消除重复代码 - 错误处理统一使用 useApiRequest.execute(),移除内联 try-catch - Modal 全部替换为 DrawerForm,保持 UI 一致性 - 净减少 ~1300 行代码(858 增 / 2136 删)
34 lines
795 B
TypeScript
34 lines
795 B
TypeScript
import { useState, useCallback, useEffect, useRef } from 'react';
|
|
|
|
export interface UseListDataReturn<T> {
|
|
data: T[];
|
|
loading: boolean;
|
|
refresh: () => Promise<void>;
|
|
}
|
|
|
|
export function useListData<T>(fetchFn: () => Promise<T[]>, autoFetch = true): UseListDataReturn<T> {
|
|
const [data, setData] = useState<T[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const fetchFnRef = useRef(fetchFn);
|
|
fetchFnRef.current = fetchFn;
|
|
|
|
const refresh = useCallback(async () => {
|
|
setLoading(true);
|
|
try {
|
|
const result = await fetchFnRef.current();
|
|
setData(result);
|
|
} catch {
|
|
setData([]);
|
|
}
|
|
setLoading(false);
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (autoFetch) {
|
|
refresh();
|
|
}
|
|
}, [refresh, autoFetch]);
|
|
|
|
return { data, loading, refresh };
|
|
}
|