【问题标题】:How do I display json data using Reactjs?如何使用 Reactjs 显示 json 数据?
【发布时间】:2025-12-13 04:30:01
【问题描述】:

我有 products.json,其中有数据。现在,我希望使用 Reactjs 渲染它。
products.json

[
  {
    "id": 1,
    "productName": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
    "price": 109.95,
    "description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
    "category": "men's clothing",
    "image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
    "specification": {}
  },
  {
    "id": 2,
    "productName": "Mens Casual Premium Slim Fit T-Shirts ",
    "price": 22.3,
    "description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.",
    "category": "men's clothing",
    "image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg",
    "specification": {}
  }
]

app.js

function App(){
       return(
       )

}

我希望通过 app.js 呈现 json 数据。

我的看法: 我是 Reactjs 和 JSON 的新手,正在考虑使用 fetch、response,但我不确定我该怎么做。 有人可以帮忙吗?

【问题讨论】:

标签: javascript json reactjs


【解决方案1】:

首先您必须将数据放入变量中 例如:

const data = [
{
  "id": 1,
  "productName": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
  "price": 109.95,
  "description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
  "category": "men's clothing",
  "image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
  "specification": {}
},
{
  "id": 2,
  "productName": "Mens Casual Premium Slim Fit T-Shirts ",
  "price": 22.3,
  "description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion 
    wear and diehard baseball fans. The Henley style round neckline includes a three-button 
    placket.",
    "category": "men's clothing",
    "image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg",
    "specification": {}
 }
]

你必须通过你的数组进行映射 像这样

function App(){
   return (
     <div>
      {data.map((d) => (
        <div key={d.id}>
          <p>ID: {d.id}</p>
          <p>Product Name: {d.productName}</p>
          <p>Price: {d.price}</p>
          <p>Description: {d.description}</p>
          <p>Category: {d.category}</p>
          <p>
             Image: <img src={d.image} width="100" />
          </p>
          <br />
          <br />
        </div>
  ))}
   </div>
);

}

然后你可以添加 CSS 让它看起来更好!

【讨论】: