graphql - 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
解决方案
你已经完成了一半只是小小的改变
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 实用程序库。
推荐阅读
- jenkins - Jenkins Pipeline - ssh-agent 找不到凭据
- ios - Xcode 11.1 错误:产生多个命令
- sql - 带有子字符串的棘手 SQL
- c# - 为什么从应用程序调用时 sql 过程会返回 0 行?
- android - 我用cordova开发了一个android应用程序,我也想把它转换成iOS
- java - java和auth0:令牌签名无效异常
- java - Java,如果勾选了多个复选框?
- r - R - object formula not found inside a function
- android - 使应用程序能够在文件对话框中打开特定扩展名不再起作用
- c - uint8_t 类型数组的元素是否总是被打包到内存的连续字节中?