javascript - 映射图像数组会导致在每个实例上重复相同的图像
问题描述
我试图将阵列图像数组中的对象映射到单独产品页面上的图像库(来自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
}
}
}
}
}
}
}
`
解决方案
您没有正确设置该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(),
推荐阅读
- html - 如何将 div 定位在 2 个其他 div 的交叉点上方?
- android - FlutterView: AppBarLayout$ScrollingViewBehavior
- python - 在 Python 中用字节解析 JSON
- ios - ARKit 没有按预期工作,如果表面很平坦,比如单色墙,则无法检测到
- php - Sqlite 没有在文本字段中正确排序日期
- r - 尝试从全球恐怖主义数据库读取数据时出现“列多于列名”错误
- javascript - click 适用于 jQuery 但不适用于 vanilla js
- javascript - 为什么 browser.runtime.getBackgroundPage() 在页面操作脚本中解析为 null?
- javascript - 当页面自动刷新但在谷歌浏览器中没有时,语音在 Firefox 中被切断
- c++11 - 如何定义堆栈对象的集合?