我正在尝试使用 NASA Images API 构建一个 React 画廊。我已经能够从 API 获取图像和 nasa_id,但我在解构标题和描述时遇到了问题。我没有使用过很多 API,也不了解此响应的格式。任何进一步的阅读或建议都会有所帮助,但现在我需要帮助弄清楚如何获得呈现“标题”和“描述”所需的响应。具体来说,"AVAIL:Description": "some description" 中的第一个冒号让我失望。我查看了 API 提供的所有其他端点,但它们似乎都没有图像的所有相同信息,至少我没有找到。
import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import api from "../utils/api";
import Preloader from "./Preloader";
export default function Details({ isLoaded }) {
const { nasa_id } = useParams();
const [image, setImage] = useState([]);
const [details, setDetails] = useState([]);
useEffect(() => {
api
.getImage(nasa_id)
.then(({ collection: { items: item } }) => {
setImage(item[0]);
})
.catch((err) => console.error(err));
}, []);
useEffect(() => {
api
.getDetails(nasa_id)
.then(({ Collection: { AVAIL:Description: description } }) => {
setDetails(description);
console.log(description);
})
.catch((err) => console.error(err));
}, []);
return (
<article className="details">
<img
className="details__image"
src={isLoaded ? image.href : <Preloader />}
alt=""
/>
<h2 className="details__title">Title: </h2>
<p className="details__subtitle">NASA ID: {nasa_id}</p>
<p className="details__info">Description: {details}</p>
<nav>
<Link to="/" className="details__info link">
Home
</Link>
</nav>
</article>
);
}
最佳答案
来自元数据 API 的响应不包含 Collection
属性。要提取描述和标题,请使用引号:
.then(({ "AVAIL:Description": description, "AVAIL:Title": title }) => {
关于reactjs - 如何使用 React 从 NASA IMAGES API 中解构所需的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73451595/