請我的代碼只回傳 JSX 而沒有來自 API 的內容。我在 console.log 時嘗試使用 fetch(),我看到了產品陣列。我的問題是如何從 API 輸出這些產品。
請幫我除錯,我嘗試了不同的方法,但此時我一直有貨。謝謝你。
產品.js 檔案
import React, { useEffect, useState } from "react";
const Products = () => {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(false);
const { title, image, price, category } = products;
useEffect(() => {
getProducts();
// eslint-disable-next-line
}, []);
const getProducts = async () => {
setLoading(true);
const res = await fetch("https://fakestoreapi.com/products");
const data = await res.json();
setProducts(data);
setLoading(false);
console.log(data);
};
if (loading) {
return <h4>Loading.....</h4>;
}
return (
<div>
{!loading && products.length === 0 ? (
<p className='center'>No logs to show....</p>
) : (
products.map((product) => (
<div class='card' style={{ width: "18rem" }} key={products.id}>
<img src={image} class='card-img-top' alt='...' />
<div class='card-body'>
<h5 class='card-title'>Card title</h5>
<p class='card-text'>
Some quick example text to build on the card title and make up
the bulk of the card's content.
</p>
</div>
<ul class='list-group list-group-flush'>
<li class='list-group-item'>{title}</li>
<li class='list-group-item'>$ {price}</li>
<li class='list-group-item'>{category}</li>
</ul>
<div class='card-body'>
<a href='#' class='card-link'>
Card link
</a>
<a href='#' class='card-link'>
Another link
</a>
</div>
</div>
))
)}
</div>
);
};
export default Products;
uj5u.com熱心網友回復:
我也不知道。但這對我有用。
products.map(({ title, image, price, category }, index) => (
<div key={index} class='card' style={{ width: "18rem" }} key={products.id}>
<img src={image} class='card-img-top' alt='...' />
<div class='card-body'>
<h5 class='card-title'>Card title</h5>
<p class='card-text'>
Some quick example text to build on the card title and make up
the bulk of the card's content.
</p>
</div>
<ul class='list-group list-group-flush'>
<li class='list-group-item'>{title}</li>
<li class='list-group-item'>$ {price}</li>
<li class='list-group-item'>{category}</li>
</ul>
<div class='card-body'>
<a href='#' class='card-link'>
Card link
</a>
<a href='#' class='card-link'>
Another link
</a>
</div>
</div>
))
)}
您需要添加{ title, image, price, category }地圖功能。我認為這是因為 map 函式不知道什么是{ title, image, price, category }變數,并且每次使用 map 函式時都需要添加一個鍵,并且不要忘記更改class=為className.
uj5u.com熱心網友回復:
您可以簡單地使用 product?.title ,product?.price,product?.category 來訪問各個欄位。這種方法比另一種方法更好,因為您不會在 API 中沒有的欄位出現錯誤。
uj5u.com熱心網友回復:
您必須首先解構您嘗試在 JSX 中使用的屬性(標題、價格、類別),然后才能顯示它們。
products.map((product) => {
const { title, price, category } = product;
return (****your JSX goes here***)})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/421439.html
標籤:
