createNode
如果其值为 null,则不会创建字段。我们有一个临时数据源,有时会返回某些字段为空的对象,尽管这种情况很少见。
我们想要使用这个查询,但是因为有时name
为空,gatsby 会删除它并导致这个查询出错。
{
allMyType {
edges {
node {
id
name
}
}
}
}
有办法解决这个问题吗?
此代码模拟用例:
const crypto = require('crypto')
exports.createPages = ({ boundActionCreators, graphql }) => {
const { createNode } = boundActionCreators
// Simulate an ephemeral data source that sometimes doesn't have all properties set
const data = {
id: '1',
name: Math.random() < 0.5 ? null : 'Paul Serby'
}
createNode({
...data,
id: data.id,
children: [],
parent: null,
internal: {
type: 'MyType',
contentDigest: crypto
.createHash(`md5`)
.update(JSON.stringify(data))
.digest(`hex`)
}
})
}
最佳答案
Gatsby 跳过 null
值。
它根据源数据构建架构并忽略空值,因此如果传入数据中的每个字段均为空或 null
,则不会创建该字段。 This issue表明在某些情况下,稀疏的字段也可能被忽略。如果您可以将该字段设置为空字符串而不是 null
(可能在您的源插件中),这可能会提供解决方法。
关于javascript - 如何确保在 Gatsby 中使用 createNode 的 graphql 查询始终存在属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507757/