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

IT技术 javascript html reactjs jsx
2021-04-28 01:02:08

下面是我的代码,在此我想添加代码以显示来自 API 的所有产品及其图像,我该怎么做?请帮忙?

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;
2个回答

我尝试了您的 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 数据中呈现元素,就像上面的示例一样

   return (
     <div>
       {products.map((product, index) => (
        <p key={index}>{product.title}</p>
       ))}
     </div>
   );
 

建议有一个产品 id,而不是使用数组索引作为 key prop。

   return (
     <div>
       {products.map(({ id, title }) => (
        <p key={id}>{title}</p>
       ))}
     </div>
   );

这个“key”props帮助 React 使用他们独特的“key”props检测和更改修改过的项目。