reactjs - 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 进行比较,但似乎没有解决问题。
解决方案
您需要首先检查字段的可用性:
<Helmet>
{wpPage.schemaMarkup.schemarepeater && wpPage.schemaMarkup.schemarepeater.map(
(schemaJson, id) =>
schemaJson !== null && (
<script type="application/ld+json" key={id}>
{JSON.stringify(schemaJson)}
</script>
)
)}
</Helmet>
推荐阅读
- java - 创建高级 HashMap、ArrayList、List
- r - 是否有可以接受附加参数的 magrittr::freduce 替代方案?
- angular - 无法从 POST 访问公开的响应标头
- android - 有人知道 Google Pixel 3 xl 的布局吗?
- three.js - 使用 FXAAShader 的抗锯齿线框看起来不太好
- linux - linux - 带有 awk 的 for 循环
- python - 如何使用 Pandas 从 XLS 文件中仅选择我需要的单元格
- reactjs - GraphQL:在上下文中找不到“客户端”或作为选项传入
- typescript - 是否可以概括一个函数并在打字稿中捕获它的签名?
- pytorch - Pytorch 图像分割迁移学习