feat: 优化 useTemplateGenerations 钩子,添加请求取消逻辑,改进数据过滤和分页处理

This commit is contained in:
康猛 2026-02-06 14:31:42 +08:00
parent d36461e62e
commit 5608458be6
1 changed files with 66 additions and 35 deletions

View File

@ -8,85 +8,108 @@ import { handleError } from './use-error'
const pageSize = 12 const pageSize = 12
// 公共工具函数
const getController = () => root.get(TemplateGenerationController)
const filterValidItems = (items: unknown[]): TemplateGeneration[] =>
(items || []).filter((item: unknown): item is TemplateGeneration => {
return Boolean(
item && typeof item === 'object' && item !== null && 'id' in item && (item as Record<string, unknown>).id,
)
})
const calculateHasMore = (items: unknown[], limit: number): boolean => Array.isArray(items) && items.length === limit
export const useTemplateGenerations = () => { export const useTemplateGenerations = () => {
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [loadingMore, setLoadingMore] = useState(false) const [loadingMore, setLoadingMore] = useState(false)
const [error, setError] = useState<ApiError | null>(null) const [error, setError] = useState<ApiError | null>(null)
const [data, setData] = useState<TemplateGeneration[]>([]) const [data, setData] = useState<TemplateGeneration[]>([])
const [hasMore, setHasMore] = useState(true)
const currentPageRef = useRef(1) const currentPageRef = useRef(1)
const hasMoreRef = useRef(true) const abortControllerRef = useRef<AbortController | null>(null)
const load = useCallback(async (params?: ListTemplateGenerationsInput) => { const load = useCallback(async (params?: ListTemplateGenerationsInput) => {
// 取消之前的请求
if (abortControllerRef.current) {
abortControllerRef.current.abort()
}
abortControllerRef.current = new AbortController()
setLoading(true) setLoading(true)
setError(null) setError(null)
currentPageRef.current = 1 currentPageRef.current = 1
const templateGeneration = root.get(TemplateGenerationController)
const { data, error } = await handleError( const limit = params?.limit || pageSize
async () => const { data: responseData, error } = await handleError(async () =>
await templateGeneration.list({ getController().list({
page: 1, page: 1,
limit: params?.limit || pageSize, limit,
...params, ...params,
}), }),
) )
// 如果请求被中止,直接返回
if (abortControllerRef.current?.signal.aborted) {
return
}
if (error) { if (error) {
setError(error) setError(error)
setLoading(false) setLoading(false)
return return { data: undefined, error }
} }
const items = data?.data || [] const items = responseData?.data || []
const filterData = filterValidItems(items)
hasMoreRef.current = items.length >= (params?.limit || pageSize) const hasMoreResult = calculateHasMore(items, limit)
const filterData = items?.filter((item) => !!item.id)
setData(filterData) setData(filterData)
setHasMore(hasMoreResult)
setLoading(false) setLoading(false)
return { data, error: null } abortControllerRef.current = null
return { data: filterData, error: null }
}, []) }, [])
const loadMore = useCallback( const loadMore = useCallback(
async (params?: Omit<ListTemplateGenerationsInput, 'page'>) => { async (params?: Omit<ListTemplateGenerationsInput, 'page'>) => {
const hasMore = hasMoreRef.current // 防止竞态条件和无效请求
if (!hasMore) return if (loading || loadingMore || !hasMore) return
setLoadingMore(true) setLoadingMore(true)
const nextPage = currentPageRef.current + 1 const nextPage = currentPageRef.current + 1
const limit = params?.limit || pageSize
const templateGeneration = root.get(TemplateGenerationController) const { data: responseData, error } = await handleError(async () =>
getController().list({
const { data: newData, error } = await handleError( page: nextPage,
async () => limit,
await templateGeneration.list({ ...params,
page: nextPage, }),
limit: params?.limit || pageSize,
...params,
}),
) )
if (error) { if (error) {
setLoadingMore(false) setLoadingMore(false)
setError(error)
return { data: undefined, error } return { data: undefined, error }
} }
const newItems = newData?.data || [] const newItems = responseData?.data || []
hasMoreRef.current = newItems.length >= (params?.limit || pageSize) const filterData = filterValidItems(newItems)
const hasMoreResult = calculateHasMore(newItems, limit)
currentPageRef.current = nextPage currentPageRef.current = nextPage
const filterData = newItems?.filter((item) => !!item.id)
setData((prev) => [...prev, ...filterData]) setData((prev) => [...prev, ...filterData])
setHasMore(hasMoreResult)
setLoadingMore(false) setLoadingMore(false)
return { data: newData, error: null } return { data: filterData, error: null }
}, },
[loading, loadingMore], [loading, loadingMore, hasMore],
) )
const refetch = useCallback( const refetch = useCallback(
(params?: ListTemplateGenerationsInput) => { (params?: ListTemplateGenerationsInput) => {
hasMoreRef.current = true setHasMore(true)
return load(params) return load(params)
}, },
[load], [load],
@ -94,7 +117,15 @@ export const useTemplateGenerations = () => {
useEffect(() => { useEffect(() => {
load() load()
}, [])
// 清理函数:组件卸载时取消未完成的请求
return () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort()
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []) // 只在组件挂载时执行一次初始加载
return { return {
data, data,
@ -104,6 +135,6 @@ export const useTemplateGenerations = () => {
load, load,
refetch, refetch,
loadMore, loadMore,
hasMore: hasMoreRef.current, hasMore,
} }
} }