Gatsby中如何将查询到的图片与JSON变量的图片字段匹配
问题原因
map方法的回调函数内的return只会将值返回到map生成的新数组,外层findImage函数没有接收该返回值,默认返回undefined。匹配单个元素不需要使用map,用Array.find更符合场景。- 匹配成功后的取值路径错误,你的GraphQL查询返回的所有图片数据都在
allFile.edges下,代码中写的data.file.childImageSharp是不存在的路径,应该直接取匹配到的当前节点的childImageSharp.gatsbyImageData。 - 函数没有显式接收
imageData作为参数,可能存在作用域取值异常的问题。
修复后的匹配函数
// imageData为你GraphQL查询返回的allFile.edges数组 function findImage(showImage, imageData) { // 用find找到第一个匹配的图片节点 const matchedImage = imageData.find(image => { console.log(image.node.name + ' vs ' + showImage) return image.node.name === showImage }) // 匹配成功返回图片数据,失败返回null避免组件报错 return matchedImage ? matchedImage.node.childImageSharp.gatsbyImageData : null }
组件使用示例
import { GatsbyImage } from "gatsby-plugin-image" // 假设你已经拿到GraphQL查询结果:const queryResult = useStaticQuery(/* 你的GraphQL查询 */) // 假设你已经引入了thisYear.json:const shows = require('./thisYear.json') function ShowList() { const imageData = queryResult.allFile.edges return ( <div> {shows.map(show => { const showImage = findImage(show.image, imageData) return ( <div key={show.title}> <h3>{show.title}</h3> <p>作者:{show.author}</p> {showImage && <GatsbyImage image={showImage} alt={show.title} />} </div> ) })} </div> ) }
优化方案(可选)
如果节目条目较多,可以提前把图片转成键值映射表,避免每次匹配都遍历整个数组,提升性能:
// 组件初始化时生成一次映射表即可 const imageMap = new Map() queryResult.allFile.edges.forEach(image => { imageMap.set(image.node.name, image.node.childImageSharp.gatsbyImageData) }) // 匹配时直接取值,无需遍历 const showImage = imageMap.get(show.image)
内容的提问来源于stack exchange,提问作者TheComeBackGuy
相关产品推荐
相关产品推荐

