首页 > 解决方案 > 在 Gatsby/Contentful 中使用 Lodash get

问题描述

Gatsby/Contentful Starter 代码示例:

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'?

标签: reactjsgraphqllodashgatsbycontentful

解决方案


通过使用 lodash 中的“get”,它可以处理某些情况,this.props.dataundefined,如果您尝试访问this.props.data.contentfulBlogPost.

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


推荐阅读