首页 > 解决方案 > GraphQL 没有返回错误但未定义

问题描述

已经找了一段时间了。我正在使用 Gatsby,控制台或终端中没有错误,但值未定义。难道是因为“文章”下的第二个“数据”?

GraphiQL 查询:

在此处输入图像描述

查询/组件代码:

import React, { Component } from 'react'
import { graphql } from 'gatsby'

// This query is executed at build time by Gatsby.
export const GatsbyQuery = graphql`
  {
    umdHub {
      articles {
        data {
          title
        }
      }
    }
  }
`

class ClientFetchingExample extends Component {
  render() {
    const {
      umdHub: { articles },
    } = this.props.data

    console.log(articles.title)
    return (
      <div style={{ textAlign: 'center', width: '600px', margin: '50px auto' }}>
        <h1>{articles.title} - Is the title of the article</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
      </div>
    )
  }
}

export default ClientFetchingExample

标签: graphqlgatsby

解决方案


你已经完成了一半只是小小的改变

const {
      umdHub: { articles },
    } = this.props.data

现在你有这样的文章对象

articles: {
    data: [
        { 
          title: 'Learning to Listen'
        },
        { 
          title: 'Second Title'
        }
        ...
    ]
}

现在你需要循环数据

import _ from 'lodash'
const data = _.get(articles, 'data', [])

_.map(data, title => {
    console.log({ title })
})

如果您只想获得第一个标题,那么

const title = _.get(articles, 'data[0].title', 'default value or blank string')

lodash 是一个提供模块化、性能和附加功能的现代 JavaScript 实用程序库。


推荐阅读