0

我在 Prismic 中有一个“单一类型”页面,其中包含一些正常的内容字段,例如uidor headline。它还具有不可重复字段的切片内容。

这是我的查询的样子:

export const homeQuery = graphql`
  query Home {
    prismicHome {
      data {
        page_title {
          text
        }
        introline {
          text
        }
        hero_headline {
          text
        }
        body {
          ... on PrismicHomeBodyProjects {
            __typename
            primary {
              client_name {
                text
              }
            }
          }
        }
      }
    }
  }
`

在我的页面中,我像这样返回它:

const IndexPage = ({ data: { prismicHome } }) => {

  return(
    <LayoutHome>
      <Hero
        introline={prismicHome.data.introline.text}
        headline={prismicHome.data.hero_headline.text}
      />
    </LayoutHome>
  )
}

但是我不知道如何在client_name不使用他们文档中使用的 ApolloClient 的情况下映射我的切片字段(即)?

我的第一次天真尝试失败并返回TypeError: Cannot read property 'data' of undefined

const projects = homeQuery.prismicHome.data.body.primary.map(({ client_name }) =>
  <div>
    <h2>{client_name}</h2>
  </div>
)
4

2 回答 2

0

尝试这个:

//First add 'slice_type' to your slice query
...

... on PrismicHomeBodyProjects {
        slice_type
        __typename
        primary {
          client_name {
            text
          }
        }
      }
 ...


// Sort and display the different slice options

const PostSlices = ({ slices }) => {

  return slices.map((slice, index) => {

    const res = (() => {

      switch (slice.slice_type) {

        case "projects":
          return (
            <div className="slice" key={index}>
              {slice content...}
            </div>
          )
        default:
          return
      }
    })()

    return res
  })
}

  // Define the Post content returned from Prismic
  export default (props) => {

  const doc = props.data.prismicHome.edges.slice(0, 1).pop();
  const slices = doc.node.data.body;

  return (
    <div>
      <PostSlices slices={slices} />
    </div>
  )
}
于 2019-11-14T14:56:12.030 回答
0

为了回答@master 的评论,我将代码位放在这里:

class ComponentName extends Component {

render() {
  const slices = this.props.data.QUERYNAME.body.map(slice => {
    switch (slice.slice_type) {
      case "slice_name":
        return (
          <Component
        prop={slice.primary.FIELDNAME.TYPE}
          />
        )
      default:
        return null // or whatever you want to return in case it breaks
    }
  })
}

return (
 {slices}
)

}
于 2019-11-15T21:57:01.277 回答