Gif未在react中加载

Gif not loading in react

提问人:Nazlul 提问时间:11/16/2023 更新时间:11/16/2023 访问量:19

问:

我尝试使用 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,它显示未定义

javascript reactjs gif giphy-api

评论

0赞 Viktor Luft 11/16/2023
“关键词”的价值是什么?
0赞 Nazlul 11/16/2023
keyword 是这里传递的搜索查询 const gifUrl = useFetch({ keyword });并在以下行中调用:const response = await fetch(https://api.giphy.com/v1/gifs/search?api_key=${API_KEY}&q=${keyword.split(" ").join("")}&limit=1);
0赞 Nazlul 11/16/2023
显然,关键字是问题所在。我没有在上下文中定义。谢谢

答: 暂无答案