处理来自get的数据输出(this.props'数据')

时间:2018-04-15 08:57:37

标签: javascript reactjs graphql gatsby

我正使用 ReactJS GatsbyJS ,使用 GraphQL Contentful 中提取数据。

获取数据是可以的,但在这种情况下,使用 react-photo-gallery Github)所提取的数据与要求不符。

以下是GraphQL查询的示例

query galleryQuery($slug: String!) {
   contentfulImageGallery(slug: {eq: $slug}) {
      summerGallery {
         sizes(maxWidth: 1500) {
            ...GatsbyContentfulSizes_withWebp_noBase64
         }
      }
   }
}

并通过定义数据

const summerGallery = get(this.props, 'data.contentfulImageGallery')

我收到

的JSON回复
{
 "data": {
    "contentfulImageGallery": {
      "summerGallery": [
        {
          "sizes": {
            "aspectRatio": 1.7779433681073025,
            "sizes": "(max-width: 1500px) 100vw, 1500px",
            "src": "http://example.com/example/img1.jpg?w=1500&q=50"
          }
        },
        {
          "sizes": {
            "aspectRatio": 1.7779433681073025,
            "sizes": "(max-width: 1500px) 100vw, 1500px",
            "src": "http://example.com/example/img2.jpg?w=1500&q=50"
          }
        }
      ]
    }
  }
}

但是我如何操纵这些数据以便我可以使用

中的图像
<Gallery photos={summerGallery}/>

作为

const summerGallery = [
  {
    src: 'http://example.com/example/img1.jpg'
    width: "NEED WIDTH"
    height: "NEED HEIGHT"
  },
  {
    src: 'http://example.com/example/img2.jpg'
    width: "NEED WIDTH"
    height: "NEED HEIGHT"
  }
]

我虽然可以通过{summerGallery.sizes.src}获取src,但它会在控制台中返回undefined并在页面上返回TypeError: Cannot read property 'src' of undefined。宽度和高度,零想法。

1 个答案:

答案 0 :(得分:1)

summerGallery.sizes.src未定义,因为summerGallery是一个没有sizes属性的数组。

您可以map summerGallery数组为所需格式:

const mappedDataArray = summerGallery.map(g => {
  return {
    src: g.sizes.src,
    width: '100vw',
    height: '1500px',
  }
})