UNPKG

aling

Version:

奇怪的组件库

36 lines (35 loc) 1.15 kB
import { useEffect, useState } from "react"; /** * @description 缓存远程资源,防止重复请求,资源会在资源地址或返回类型变化后重新请求 * @param src - 需要加载的资源地址 * @param type - 缓存的类型url、blob、arrayBuffer * @returns 缓存资源的类型,可以是 string, Blob, or ArrayBuffer. */ export default (src, type = "url") => { const [res, setRes] = useState(); useEffect(() => { if (type == "blob") { fetch(src).then((response) => { response.blob().then((b) => { setRes(b); }); }); } if (type === "arrayBuffer") { fetch(src).then((response) => { response.arrayBuffer().then((a) => { setRes(a); }); }); } if (type === "url") { fetch(src).then((response) => { response.blob().then((b) => { const url = URL.createObjectURL(b); setRes(url); }); }); } }, [src]); return res; };