代码之家  ›  专栏  ›  技术社区  ›  StackUnderFlow

使用Map()函数提取带有ReactJS的双嵌套JSON数据

  •  0
  • StackUnderFlow  · 技术社区  · 5 年前

    我试图在“细节”部分下面的“图片”对象中提取出各个图片。

    好像什么都没印出来。在细节中寻找正确的拉入方式。图像。图像1、2或3。

    以下是我目前使用的JSON数据:

    {
      "books": [
        {
          "title": "title 1",
          "image": "/image1.jpg"
        },
        {
          "title": "title 2",
          "image": "/image2.jpg"
        }
      ],
      "details": [
        {
          "author": "book author",
          "name": "Book name",
          "price": 34.99,
          "publisher": "Penguin Books",
          "images": [
            {
              "image1": "/image1.jpg",
              "image2": "/image2.jpg",
              "image3": "/image3.jpg"
            }
          ]
        }
      ]
    }
    

    这里还有我在book组件中进行的json调用:

    {staticdata.details.map(detail => (
      <Book
        book_name={detail.author}
        book_price={detail.price}
        image={detail.images.image1}
      />
    ))}
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   Nick    5 年前

    下面是访问这些嵌套属性并将其记录到控制台的示例。看来你的尝试基本上是正确的,但是 images 是一个数组。

    const data = {
      "books": [
        {
          "title": "title 1",
          "image": "/image1.jpg"
        },
        {
          "title": "title 2",
          "image": "/image2.jpg"
        }
      ],
      "details": [
        {
          "author": "book author",
          "name": "Book name",
          "price": 34.99,
          "publisher": "Penguin Books",
          "images": [
            {
              "image1": "/image1.jpg",
              "image2": "/image2.jpg",
              "image3": "/image3.jpg"
            }
          ]
        }
      ]
    }
    
    data.details.map(detail => {
      console.log(detail.author, detail.price, detail.images[0].image1);
    });