使用 GatsbyImage - 我不断收到错误失败的道具类型:道具“图像”在“GatsbyImage”中标记为必需,但其值为“未定义”

问题描述

我的所有艺术家数据都在一个 json 文件中:artist.json。在那里我还有我试图为每个艺术家渲染的图像名称。我尝试使用exports.sourceNodes,但我一定做错了什么。 您可以在此问题上提供的任何帮助都将非常有帮助,因为我对此还是个新手,并且很难将文档中的信息内化。我的图像的路径是:图像/艺术家/头像/ 这是我的 gatsby-config.js 文件

const path = require('path')

module.exports = {
  siteMetadata: {
    title: 'Platform Showcase',},plugins: [
    'gatsby-plugin-gatsby-cloud',// {
    //   resolve: "gatsby-plugin-google-analytics",//   options: {
    //     trackingId: "",//   },// },'gatsby-plugin-react-helmet','gatsby-plugin-sitemap',{
      resolve: 'gatsby-plugin-manifest',options: {
        icon: 'src/images/icon.png','gatsby-plugin-mdx','gatsby-plugin-image','gatsby-plugin-sharp','gatsby-transformer-sharp',{
      resolve: 'gatsby-source-filesystem',options: {
        name: 'images',path: './src/images/',__key: 'images',{
      resolve: `gatsby-source-filesystem`,options: {
        name: `headshots`,path: `${__dirname}/src/images/artists/headshots`,__key: 'headshots',options: {
        name: 'pages',path: './src/pages/',__key: 'pages',`gatsby-theme-material-ui`,`gatsby-transformer-json`,options: {
        path: `./src/data/`,{
      resolve: 'gatsby-plugin-root-import',options: {
        src: path.join(__dirname,'src'),components: path.join(__dirname,'src/components'),containers: path.join(__dirname,'src/containers'),helpers: path.join(__dirname,'src/helpers'),images: path.join(__dirname,'src/images'),],}

这是我的 gatsby-node.js 文件

const path = require(`path`)
const artists = require('./src/data/artists.json')
const IMAGE_PATH = './src/images/artists/headshots/'
const { createFilePath } = require(`gatsby-source-filesystem`)

exports.sourceNodes = ({ actions,createNodeId,createContentDigest }) => {
  artists.forEach((card) => {
    const {
      firstName,lastName,currentTeam,bio,city,whatWelove,image,featuredVideo,recentPerformance,} = card

    const { name,ext } = path.parse(image)
    const absolutePath = path.resolve(__dirname,IMAGE_PATH,image)

    const data = {
      name,ext,absolutePath,extension: ext.substring(1),}

    const imageNode = {
      ...data,id: createNodeId(`card-image-${name}`),internal: {
        type: 'ArtistsCardImage',contentDigest: createContentDigest(data),}
    // actions.create(imageNode)
    const node = {
      firstName,image: imageNode,// image,id: createNodeId(`card-${firstName}${lastName}`),internal: {
        type: 'ArtistsCard',contentDigest: createContentDigest(card),}
    actions.createNode(node)
  })
}

这是我的艺术家组件:

import React from 'react'
import PropTypes from 'prop-types'
import { StaticImage } from 'gatsby-plugin-image'
import { GatsbyImage,getimage } from 'gatsby-plugin-image'
import { useStyles } from './styles'


const ArtistsPage = ({ artists }) => {
  const classes = useStyles()
  const image = getimage(artists.allArtistsCard.nodes)
 return (
...
<div className={classes.flexContainer}>
          {artists.allArtistsCard.nodes
 .map(({ firstName,currentTeam },idx) => {
return (
                <div className={classes.flexItem} key={idx}>
                  <div>
                    <GatsbyImage image={image} alt='artist-image' />
</div>
 <div className={classes.artistCardName}>
                    {`${firstName} ${lastName}`.toupperCase()}
                  </div>
                  <div className={classes.artistCardText}>{city}</div>
                  <div className={classes.artistCardText}>{currentTeam}</div>
</div>
  )
            })}
...
  )
}

ArtistsPage.propTypes = {
  firstName: PropTypes.string,lastName: PropTypes.string,currentTeam: PropTypes.string,city: PropTypes.string,image: PropTypes.string,artists: PropTypes.array.isrequired,}
export default ArtistsPage

这是我的 json 数据文件的设置: 数据/artist.json

[
  {
    "artistId": 1,"firstName": ["Carlo"],"lastName": ["Darang"],"bio": "Carlo Darang started his training in 2008 at Studio 429 where he joined his first dance team,Breakthrough. He later joined Choreo Cookies in 2009,and has continued to be a part of the team till present day. He currently directs the team with Jason Patio and Chris Martin. He also directs another adult team called GWOWNUPS with Amor Ledesma. Outside directing,Carlo enjoys teaching at both Building Block,Studio FX and Culture Shock Dance Center. He also has had many opportunities to teach outside of San Diego,both domestically and internationally. Carlo hopes to just be the same type of figure to others as his mentors were to him.","highlight": "","events": ["Spring 2019"],"featuredVideo": "","currentTeam": "","twitter": "","instagram": "https://www.instagram.com/carlodarang/","city": "San Diego","tiktok": "","youtube": "","email": "","address": "","phoneNumber": "","whatWelove": "","recentPerformance": "","image": "Carlo Darang Headshot.jpg"
  },]

我真的不明白这是为什么: const image = getimage(artists.allArtistsCard.nodes) 返回未定义。 非常感谢您的帮助!

解决方法

我认为您的代码应该如下所示:

const ArtistsPage = ({ artists }) => {
  const classes = useStyles()
 return (
...
<div className={classes.flexContainer}>
          {artists.allArtistsCard.nodes
 .map(({ firstName,lastName,city,currentTeam },idx) => {
  let image = getImage(artists.allArtistsCard.nodes[idx])

return (
                <div className={classes.flexItem} key={idx}>
                  <div>
                    <GatsbyImage image={image} alt='artist-image' />
</div>
 <div className={classes.artistCardName}>
                    {`${firstName} ${lastName}`.toUpperCase()}
                  </div>
                  <div className={classes.artistCardText}>{city}</div>
                  <div className={classes.artistCardText}>{currentTeam}</div>
</div>
  )
            })}
...
  )
}

我真的不明白为什么会这样:const image = getImage(artists.allArtistsCard.nodes) 返回为 undefined

因为在您之前的代码中,image 是一个数组,而不是图像节点本身。在您的场景中,您的 image 变量应该在循环内,以便在每次迭代中被覆盖并获取图像节点。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...