graphql - 在 Gatsby 上渲染 Contentful Reference (many) 数组

标签 graphql gatsby contentful

我对使用 Contentful 及其引用(许多)字段类型还很陌生。我有一种引用类型,它包含许多产品名称。在 GraphQL 中,我可以看到我所有的产品名称都在显示,但是当我尝试在 Gatsby 上渲染它时,我没有看到任何显示(产品名称:数组)。这是我的 GraphQL

{
  allContentfulAppetizerMenuSection {
      nodes {
        menuItemReferences {
          productName
        }
      }
  }
}

这是我的代码...

import React from 'react';
import { graphql, StaticQuery } from 'gatsby';

const Products = () => (

  <StaticQuery
  query={graphql`
    query MyQuery {
        allContentfulAppetizerMenuSection {
            nodes {
              menuItemReferences {
                productName
              }
            }
        }
    }
  `}

  render={data => (
    <div>
        {data.allContentfulAppetizerMenuSection.nodes.map(({ menuItemReferences }, i) => (
        <div key={i}>
            {menuItemReferences.productName}
        </div>
      ))}
    </div>
    )}
  />
)
  
export default Products;

任何帮助将不胜感激。

最佳答案

尝试:

const Products = () => {
  const data = useStaticQuery(graphql`
      query {
          allContentfulAppetizerMenuSection {
              nodes {
                  menuItemReferences {
                      productName
                  }
              }
          }
      }
  `);

  return <div>
    {data.allContentfulAppetizerMenuSection.nodes.map(({ menuItemReferences }, i) => {
      return <div key={i}>
        {menuItemReferences.productName}
      </div>;
    })}
  </div>;
};

export default Products;

注意 useStaticQuery 的用法钩子(Hook)和循环中的 return 语句。

useStaticQuery 的重构产生了更清晰和可重用的代码,但它的想法完全相同,如果您更熟悉旧的 StaticQuery,则可以保留它。

如果错误仍然存​​在,请尝试在循环内进行调试。

关于graphql - 在 Gatsby 上渲染 Contentful Reference (many) 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64490137/

相关文章:

node.js - Express、Node js 中的 graphql 错误

reactjs - 有没有办法在 MockedProvider - Apollo Client 中模拟 refetch?

node.js - GraphiQL 返回零突变

gatsby - 如何使用Gatsby将任意文件添加到/public?

Gatsby 未安装

javascript - GraphQL 查询错误它说未知类型 "ContentfulSizes"

javascript - 在 Angular 中显示 ContentFul RichText

ruby-on-rails - 对于 Rails 和 GraphQL 项目,如何定义多个同名查询?

javascript - Gatsby Remark 图像和 Gatsby 图像之间的区别?

javascript - 动态组件上的 Angular 5 下一个按钮