【问题标题】:Show Contentful product using GatsbyJS使用 GatsbyJS 展示内容丰富的产品
【发布时间】:2018-01-24 03:13:23
【问题描述】:

我正在将来自 Contentful api 的数据提取到 gatsby 中,一切似乎都很好。但是,当我实现将内容数据拉入我的 index.js 文件的组件时,我不断收到未定义的错误。

WebpackError: Cannot read property 'allContentfulProduct' of undefined

Product.js:

import React from "react"

const Product = ({data}) => {
  const assets = data.allContentfulProduct.edges[0].node
  const { productName } = assets;

 return (
    <div>
      {productName}
    </div>
  )
};

export default Product;



export const pageQuery = graphql`
  query ImageAPIExamples {
    allContentfulProduct {
      edges {
        node {
          id
          productName
        }
      }
    }
  }
`

索引.JS

import React from 'react';
import Products from '../components/products/image';

const IndexPage = props =>
  (<main>
    Hello
  </main>);

export default IndexPage;

【问题讨论】:

    标签: reactjs contentful gatsby


    【解决方案1】:

    看来我可以通过传递 props 并在 index.js 页面上查询数据来解决这个问题。

    解决方案:

    Index.js:

    import React from 'react';
    import Products from '../components/products/image';
    
    
    const IndexPage = props =>
      (<main>
        <Products data={props.data.allContentfulProduct.edges[0].node} />
      </main>);
    
    export default IndexPage;
    
    export const pageQuery = graphql`
      query IndexQuery {
        allContentfulProduct {
          edges {
            node {
              id
              productName
              image {
                file{
                  url
                }
              }
            }
          }
        }
      }
    `;
    

    【讨论】:

    • 您只能从提供给createPage() 的组件中从GraphQL 中获取数据并导出pageQuery 魔术变量。如果您的 Products.js 是从 index.js 导入的,则它无法从 GraphQL 中获取。这是为了让 Gatsby 静态编译你的数据。
    猜你喜欢
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    相关资源
    最近更新 更多