Files
timeline-frontend/src/components/Hooks/useFetchImageUrl.ts

55 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-07-22 22:52:55 +08:00
import { useRequest } from '@umijs/max';
import { useEffect, useRef, useState } from 'react';
import {fetchImageLowRes} from "@/services/file/api";
2025-07-22 22:52:55 +08:00
// 简单内存缓存,避免因虚拟滚动重复请求同一张图片
const imageUrlCache = new Map<string, string>();
2025-07-22 22:52:55 +08:00
const useFetchImageUrl = (imageInstanceId: string) => {
const [imageUrl, setImageUrl] = useState("error");
const retryRef = useRef(0);
2025-08-04 16:56:39 +08:00
const { data: response, run, loading } = useRequest(
() => fetchImageLowRes(imageInstanceId),
2025-07-22 22:52:55 +08:00
{
manual: true,
onSuccess: (data) => {
if (data) {
const objectUrl = URL.createObjectURL(data);
imageUrlCache.set(imageInstanceId, objectUrl);
setImageUrl(objectUrl);
} else {
setImageUrl("error");
}
retryRef.current = 0;
},
onError: () => {
if (retryRef.current < 2) {
retryRef.current += 1;
run();
} else {
setImageUrl("error");
imageUrlCache.set(imageInstanceId, "error");
retryRef.current = 0;
}
2025-07-22 22:52:55 +08:00
},
},
);
2025-07-22 22:52:55 +08:00
useEffect(() => {
if (imageInstanceId) {
retryRef.current = 0;
const cached = imageUrlCache.get(imageInstanceId);
if (cached) {
setImageUrl(cached);
} else {
run();
}
2025-08-05 19:02:14 +08:00
} else {
setImageUrl("error");
2025-07-22 22:52:55 +08:00
}
}, [imageInstanceId, run]);
2025-08-04 16:56:39 +08:00
return {imageUrl, loading};
2025-07-22 22:52:55 +08:00
};
export default useFetchImageUrl;