首页 > 解决方案 > 映射图像数组会导致在每个实例上重复相同的图像

问题描述

我试图将阵列图像数组中的对象映射到单独产品页面上的图像库(来自strapi)。出现正确数量的图像,但在它们上重复相同的图像。即使在不应在其各自数组中包含该图像的产品页面上也是如此。示例 - https://imgur.com/a/PKlpofy

我检查了源和图像 src 链接都是同一图像的不同版本。- https://imgur.com/a/968w77b

GraphIQL - https://imgur.com/a/HvgMA8r

任何关于我哪里出错的指示都会很棒!如果您需要更多信息,请告诉我。

代码-

<div className="image-grid">
                {data.home.galleryImage.map((image, id, caption) => (
                    
                      <Image fluid={image.formats.medium.childImageSharp.fluid} alt="hh" key={id} class="galleryimg" thumbnail/> 
                   
                ))  
                }
                </div>
        </div>

GraphQL 查询 -

export const query = graphql`
      query GetSingleHome($slug: String) {
        home: strapiHomes(slug: { eq: $slug }) {
        galleryImage {
          id 
          formats {
            medium {
              childImageSharp {
               fluid(maxWidth: 400, maxHeight: 250) {
                 ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
        }
      }
    `

标签: javascriptreactjsgraphqlgatsby

解决方案


您没有正确设置该key值。image是可迭代对象,只是命名您的每个索引的一种方式,galleryImage因此id, 并不代表id图像本身的 。

将其更改为:

<div className="image-grid">
  {data.home.galleryImage.map((image) => (
     <Image fluid={image.formats.medium.childImageSharp.fluid} alt="hh" key={image.id} class="galleryimg" thumbnail/>  
   ))}
</div>

要访问嵌套的图像属性,您需要访问其子属性,就像您在 中所做的那样image.formats,访问formats位置,但使用image.id.

有关更多详细信息,您可以查看MDN 文档

此外,如果循环打印相同的图像,则在id从 Strapi 创建数据节点时,在内部未从 GraphQL 正确设置。您可以自定义 GraphQL 节点架构以添加自定义参数,以便使用 Gatsby 提供的不同 API 绕过此限制,这createRemoteFileNode应该符合您的要求。

 const { createRemoteFileNode } = require(`gatsby-source-filesystem`);
    
    exports.onCreateNode = async ({ node, actions, store, cache }) => {
      const { createNode, createNodeField } = actions;
    
      if (node.internal.type !== null && node.internal.type === "StrapiPortfolio") {
        for (const category of node.category) {
          for (const image of category.images) {
            console.log(image);
            const fileNode = await createRemoteFileNode({
              url: "http://localhost:1337" + image.url,
              store,
              cache,
              createNode,
              createNodeId: (id) => image.id.toString(),
            });
    
            if (fileNode) {
              image.localFile___NODE = fileNode.id;
            }
          }
        }
      }
    };

资料来源:如何使用 Graphql 从 Strapi 查询 Gatsby 中的多个图像

根据您的数据结构,您可能需要更改循环和其他一些参数。在这种情况下,图像位于category节点内,因此必须通过嵌套两个不同的循环来推断。

这个想法是遍历所有图像节点并添加以下localFile___NODE字段:

  image.localFile___NODE = fileNode.id;

id之前创建于:

  createNodeId: (id) => image.id.toString(),

推荐阅读