【问题标题】:TypeError: Cannot read property 'data' of undefined ....src/pages/index.js in GatsbyTypeError:无法读取 Gatsby 中未定义 ....src/pages/index.js 的属性“数据”
【发布时间】:2020-01-09 22:56:31
【问题描述】:

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

....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得到data.img.childImageSharp.fluid

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`,
  ],
}

【问题讨论】:

  • 您不需要以某种方式将您的IndexPage 连接到graphQL。
  • 我该怎么做?我是 gatsby 的新手,看不懂。我按照类似于 gatsbyjs.org/docs/page-query 的教程进行操作
  • 向我们展示您的gatsby-config.js。您应该有指向您的图像文件的gatsby-source-filesystem。你的gatsby-config.js 中有这个插件https://www.gatsbyjs.org/packages/gatsby-source-filesystem/ 吗?
  • @EliteRaceElephant 我刚刚添加了gatsby-config.js。是的,我已经安装了那个插件。
  • 您似乎已正确设置所有内容。您可以尝试记录整个 props 对象吗?

标签: javascript reactjs graphql gatsby graphql-js


【解决方案1】:

这都是因为一个错字。我忘记了 GatsbyImageSharpFluid_tracedSVG

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

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2021-02-06
    • 2021-03-09
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多