【发布时间】: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