首页 > 解决方案 > GatsbyJS:从 ACF 转发器字段创建 json/结构化数据

问题描述

我正在尝试创建一个包含结构化数据的 ACF 中继器字段。然后我想在我的 GatsbyJS 站点中输出该字段。对于这个任务,我使用 React 头盔。

我的代码:

      <Helmet>
        {wpPage.schemaMarkup.schemarepeater.map(
          (schemaJson, id) =>
            schemaJson !== null && (
              <script type="application/ld+json" key={id}>
                {JSON.stringify(schemaJson)}
              </script>
            )
        )}
      </Helmet>

我在模板文件中的 GraphQL Schema:

wpPage(id: { eq: $id }) {
      __typename
      id
      uri
      content
      title
      schemaMarkup {
        schemarepeater {
          schemaJson
        }
      }
    }

代码有点工作。唯一的问题是,如果页面在我的 ACF 中继器字段中不包含值(并非所有页面都应该具有值),它会返回错误:WebpackError: TypeError: Cannot read property 'map' of null

我曾尝试与 !== null 进行比较,但似乎没有解决问题。

标签: reactjsgraphqlgatsby

解决方案


您需要首先检查字段的可用性:

  <Helmet>
    {wpPage.schemaMarkup.schemarepeater && wpPage.schemaMarkup.schemarepeater.map(
      (schemaJson, id) =>
        schemaJson !== null && (
          <script type="application/ld+json" key={id}>
            {JSON.stringify(schemaJson)}
          </script>
        )
    )}
  </Helmet>

推荐阅读