這就是通過單擊它們來獲取 gif 的 id 的方式,但是我收到了這個錯誤 Uncaught TypeError: Cannot read properties of undefined (reading 'fixed_height'),我想在 UI 中顯示 fixed_height。
<>
{Object.keys(gifs).length === 0 ? (
<div>loading...</div>
) : (
<div className="gif-section">
{gifs.data.map((items) => {
return (
<a href="#" className="image-gifs" key={items.id}>
<img
className="live-gifs"
onClick={() => getGifId(items.id)}
src={items.images.fixed_height.url}
alt="我試圖通過單擊特定的 gif 在 ui 中顯示 gif,當我通過地圖獲取資料時出現型別錯誤"
/>
</a>
);
})}
</div>
)}
</>
這里我通過 id 獲取 gif 并顯示它。

import axios from "axios";
import { useState } from "react";
import { useEffect } from "react";
const GifInText = ({ gifId }) => {
const [post, setPost] = useState({});
console.log("post:", post);
const fetchData = async () => {
axios
.get(`https://api.giphy.com/v1/gifs/${gifId}`, {
params: {
api_key: "Xoa3mXrWxKXw6lJscrKUTsbZsXLbGuGY",
gif_id: gifId
}
})
.catch((error) => {
console.log("error at fetching gifID2", error);
})
.then((response) => {
setPost(response.data);
});
};
useEffect(() => {
fetchData();
}, []);
return (
<div>
{Object.values(post).length &&
Object.values(post).map((items) => {
return (
<>
<h1>{items.id}</h1>
<img
className="live-gifs"
src={items.images.fixed_height.url}
alt="..."
/>
</>
);
})}
</div>
);
};
export default GifInText;
在此處輸入影像描述
uj5u.com熱心網友回復:
根據您分享的影像。如果post是具有單個 gif 資料的物件,您可以簡單地使用post.data.url而不是items.images.fixed_height.url回圈使用 Object.values(post).
{post.data.url && (
<>
<h1>{post.id}</h1>
<img
className="live-gifs"
src={post.data.url}
alt="..."
/>
</>
)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/440157.html
標籤:javascript 反应 api 目的
