问题
Below is my code, in this I want to add code to display all the products with its image from an API, how can I do that? Please help?
import React, {useState, useEffect} from 'react'
import "bootstrap/dist/css/bootstrap.min.css"
import Axios from "axios"
function Products() {
const [products, setProducts] = useState({});
const fetchProducts = async () => {
const {data} = await Axios.get('https://api.test.ts/demo/test');
const products= data
setProducts(products);
};
useEffect(() => {
fetchProducts()
}, []);
return(
<div>
Want to Display list of products from API
</div>
)
}
export default Products;
回答1:
I tried your URL for fetching products but it is showing as not reachable so I have coded this simple app using https://jsonplaceholder.typicode.com
API of the list of todos.
Hope this example helps you understand how to fetch and display items from fetched data.
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 Link
Here is another example, where the returned data is in the form of an object instead of an array in the above Example:
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>
);
}
Here is the Codesandbox Example Showing how to Render elements from JSON data returned in the form of the object instead of Array Like the above example
回答2:
return (
<div>
{products.map((product, index) => (
<p key={index}>{product.title}</p>
))}
</div>
);
It's recommended to have a product id, instead of using the array index as a key prop.
return (
<div>
{products.map(({ id, title }) => (
<p key={id}>{title}</p>
))}
</div>
);
That 'key' prop helps React detect & change the modified items using their unique 'key' prop.
来源:https://stackoverflow.com/questions/65080448/how-to-display-all-items-from-an-api-in-react-js