Проект Gatsby-ContentFul: невозможно получить данные из Graphql на моей странице - PullRequest
0 голосов
/ 30 июня 2019

Я решил создать небольшой проект по новым технологиям, и я выбрал Гэтсби. Чтобы сообщить вам, я не работаю с React и GraphQl раньше. Так что благодаря Гэтсби я вижу и другие технологии. Итак, на данный момент я пытаюсь сделать страницу опроса индекса, где нижний колонтитул и верхний колонтитул могут быть изменены. Я беру за свой бэкэнд Contentful и мне удается установить связь между контентом из ContentFul и нижним колонтитулом моего компонента. Но когда я пытаюсь сделать запрос на странице index.js невозможно получить данные, но они существуют (я проверил на graphql).

Я пытаюсь сделать запрос в компоненте, сделать запрос в хуке, а затем вызвать хук. Но ничего не меняется всегда неопределенно

По моему index.js:


const  query = graphql`
    query header{
        contentfulHeader {
          id
          titleCard
          descriptionCard
          logoCard {
            file {
              url
            }
          }
        }
      }
    `

const SurveyTitleCard = props => {
  return (
    <>
      <div className="row">
        <div className="survey-title card blue-grey darken-3 col s10 offset-s1 m6 offset-m3">
          <div className="card-content grey-text text-lighten-3 center-align">
            <div className="row logo valign-wrapper">
              <div className="col s6 offset-s3 m4 offset-m4">
                <img
                  className="responsive-img"
                  src=""
                  alt="logo company"
                />
              </div>
            </div>
            <div className="card-title">
             {query.contentfulHeader.titleCard}
            </div>
            <p>We would love to hear your anonymous thoughts and feedback</p>
          </div>
        </div>
      </div>
    </>
  )
}
// INDEX PAGE
const IndexPage = () => (
  <Layout>
    <SEO title="Home" />
    <SurveyTitleCard />
  </Layout>
)

Вот данные из GraphQl: enter image description here

Вот мой gatsby-config.js:

module.exports = {
  siteMetadata: {
    title: `Gatsby Default Starter`,
    description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
    author: `@AntoineB`,
  },

  plugins: [
    {
      resolve: `gatsby-source-contentful`,
      options:{
        spaceId: `MY_SPACE_ID`,
        accessToken: `MY_ACCESS_TOKEN`,
      },
    },
    `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/gatsby-icon.png`, // 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 Ответ

1 голос
/ 30 июня 2019

См. Документы по запросам данных в компонентах с использованием StaticQuery

import React from "react"
import { StaticQuery, graphql } from "gatsby"

export default () => (
  <StaticQuery
    query={graphql`
        query header{
        contentfulHeader {
          id
          titleCard
          descriptionCard
          logoCard {
            file {
              url
            }
          }
        }
      }
    `}
    render={data => (
      <>
        <div className="row">
          <div className="survey-title card blue-grey darken-3 col s10 offset-s1 m6 offset-m3">
            <div className="card-content grey-text text-lighten-3 center-align">
              <div className="row logo valign-wrapper">
                <div className="col s6 offset-s3 m4 offset-m4">
                  <img
                    className="responsive-img"
                    src=""
                    alt="logo company"
                  />
                </div>
              </div>
              <div className="card-title">
               {data.contentfulHeader.titleCard}
              </div>
              <p>We would love to hear your anonymous thoughts and feedback</p>
            </div>
          </div>
        </div>
      </>
    )}
  />
)
...