我尝试了您的 URL 来获取产品,但它显示为无法访问,因此我使用https://jsonplaceholder.typicode.com
待办事项列表的 API 对这个简单的应用程序进行了编码。
希望这个例子能帮助你理解如何从获取的数据中获取和显示项目。
import React, { useState, useEffect } from "react";
import "./styles.css";
import Axios from "axios";
function App() {
const [products, setProducts] = useState([]);
const fetchProducts = async () => {
const { data } = await Axios.get(
"https://jsonplaceholder.typicode.com/todos/"
);
const products = data;
setProducts(products);
console.log(products);
};
useEffect(() => {
fetchProducts();
}, []);
return (
<div>
{products.map((product) => (
<p key={product.id}>{product.title}</p>
))}
</div>
);
}
export default App;
CodeScandbox 链接
这是另一个示例,其中返回的数据采用对象的形式,而不是上述示例中的数组:
import React, { useState, useEffect } from "react";
import "./styles.css";
import Axios from "axios";
const productsData = {
note: "",
notification: "",
Books: [
{
bookID: 65342,
img: "https://source.unsplash.com/200x300/?book",
year: 2018,
bookTitle: "Story Time",
LibraryInfo: {
Status: "Out",
returnDate: "7 Jan"
}
},
{
bookID: 65332,
img: "https://source.unsplash.com/200x300/?book",
year: 2018,
bookTitle: "Story Time",
LibraryInfo: {
Status: "Out",
returnDate: "7 Jan"
}
}
]
};
export default function App() {
const [products, setData] = useState(productsData);
const [toggle, setToggle] = useState({});
useEffect(() => {
setData({});
Axios.get("https://stylmate1.firebaseio.com/hair.json").then((response) => {
// console.log(response.data);
setData(productsData);
});
}, [toggle]);
return (
<div className="App">
{/* <button onClick={() => setToggle(!toggle)}>fetch</button> */}
{products?.["Books"]?.length &&
products["Books"].map((product) => (
<div key={Math.random() * 10000}>
<img src={product.img} width="200" alt="" />
<p>{product.bookTitle}</p>
<p>{product.year}</p>
<p>
{"Library Status: " +
product.LibraryInfo.Status +
"\n" +
product.LibraryInfo.returnDate}
</p>
<p></p>
</div>
))}
</div>
);
}
这里是Codesandbox 示例,展示了如何从以对象而不是数组的形式返回的 JSON 数据中呈现元素,就像上面的示例一样