使用 Lodash 进入 Gatsby/Contentful

Use of Lodash get in Gatsby/Contentful

Gatsby/Contentful 起始代码示例:

import get from 'lodash/get'
    ...
    const post = get(this.props, 'data.contentfulBlogPost')
    const siteTitle = get(this.props, 'data.site.siteMetadata.title')

为什么他们在 html 代码中使用 lodash 'get' 而不是直接引用 graphql-query 结果 'data'?

通过使用 lodash 中的 'get',它可以处理一些 this.props.dataundefined 的情况,以避免在您尝试访问 this.props.data.contentfulBlogPost 时代码抛出一些错误.

您也可以使用 this.props?.data?.contentfulBlogPost