简体   繁体   English

如何在 React JS 中显示 API 中的所有项目?

[英]How to display all items from an API in React JS?

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?下面是我的代码,在此我想添加代码以显示来自 API 的图像的所有产品,我该怎么做? 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;

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. 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 CodeScandbox 链接

Here is another example, where the returned data is in the form of an object instead of an array in the above Example:这是另一个示例,其中返回的数据采用 object 的形式,而不是上述示例中的数组:

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这是Codesandbox示例,显示如何从 JSON 数据中渲染元素,该数据以 object 的形式返回,而不是数组

   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.建议使用产品 id,而不是使用数组索引作为 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.那个 'key' 道具帮助 React 使用他们独特的 'key' 道具检测和更改修改过的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM