TypeError:无法读取Gatsby中未定义.... src / pages / index.js的属性“ data”

时间:2019-09-07 09:54:52

标签: javascript reactjs graphql gatsby graphql-js

我从undefined(位于..src/pages/index.js文件夹中)的道具中以components的形式获取数据。但是,我在GraphiQL中获取数据。我是盖茨比的新手。如何从道具中获取数据?

.... src / pages / index.js

import { Link, graphql } from "gatsby"

const IndexPage = ({ data }) => (
  <>
    {console.log("data: ", data)} //data: undefined
  </>
)

export const query = graphql`
  {
    img: file(relativePath: { eq: "default-background.jpeg" }) {
      childImageSharp {
        fluid {
          ...GatsbyImageSharpFluid_traceSVG
        }
      }
    }
  }
`

export default IndexPage

GraphiQL(在浏览器中):

{
 img: file(relativePath: {eq: "default-background.jpeg"}) {
   childImageSharp {
     fluid {
       src
     }
   }
 }
}
来自GraphiQL的

响应:

  "data": {
    "img": {
      "childImageSharp": {
        "fluid": {
          "src": "/static/0b5a2394b40bdf231dc6685a512baeff/bc3a8/default-background.jpg"
        }
      }
    }
  }
}

我的目标是从道具data.img.childImageSharp.fluid中获得data

gatsby-config.js

module.exports = {
  siteMetadata: {
    title: `Regular Joe's`,
    description: `some description.`,
    author: `@gatsbyjs`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/logo.svg`, // This path is relative to the root of the site.
      },
    },
    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.dev/offline
    // `gatsby-plugin-offline`,
  ],
}

1 个答案:

答案 0 :(得分:0)

这完全是因为输入错误。.我在 GatsbyImageSharpFluid_trace d SVG

中忘记了 d
export const query = graphql`
  {
    img: file(relativePath: { eq: "default-background.jpeg" }) {
      childImageSharp {
        fluid {
          ...GatsbyImageSharpFluid_tracedSVG //there was a typo in GatsbyImageSharpFluid_traceSVG
        }
      }
    }
  }`