提问人:Nazlul 提问时间:11/16/2023 更新时间:11/16/2023 访问量:19
Gif未在react中加载
Gif not loading in react
问:
我尝试使用 API 从 giphy 获取 gif,bu[在此处输入图像描述][1]但 gif 无法加载
useFetch.jsx
import { useEffect, useState } from 'react';
const API_KEY = import.meta.env.VITE_GIPHY_API;
const useFetch = ({ keyword }) => {
const [gifUrl, setGifUrl] = useState("");
const fetchGifs = async () => {
try {
const response = await fetch(`https://api.giphy.com/v1/gifs/search?api_key=${API_KEY}&q=${keyword.split(" ").join("")}&limit=1`);
const { data } = await response.json(); ;
setGifUrl(data[0]?.images?.downsized_medium.url);
} catch(error) {
setGifUrl("https://metro.co.uk/wp-content/uploads/2015/05/pokemon_crying.gif?quality=90&strip=all&zoom=1&resize=500%2C284");
}
};
useEffect(() => {
if(keyword) fetchGifs();
}, [keyword]);
return gifUrl;
};
export default useFetch;
我是如何导入和实现的
import useFetch from '../hooks/useFetch';
const TransactionCard = ({ addressTo, addressFrom, timestamp, message, keyword, amount,
url }) => {
const gifUrl = useFetch({ keyword });
console.log("GIF URL:", gifUrl);
console.log("Fallback URL:", url);
return (.....
.........
<img
src = {gifUrl || url}
alt ="gif"
className='w-full h-64 2xl:h-96 rounded-md shadow-lg object-cover'
onError={(e) => {
console.error("Error loading image:", e);
}}
/>
......
我试图控制台.log url,它显示未定义
答: 暂无答案
评论
https://api.giphy.com/v1/gifs/search?api_key=${API_KEY}&q=${keyword.split(" ").join("")}&limit=1
);