我正试图用盖茨比做一个博客。
我想使用Asciidoc而不是Markdown,所以我写了以下关于官方代码的代码。
const blogArticleTemplate = path.resolve(
"./src/components/templates/article/index.tsx"
)
const articles = result.data.allAsciidoc.edges
if (0 < articles.length) {
articles.forEach(( node, index ) => {
const slug = node.pageAttributes.slug
const previousArticle = index === 0 ? null : articles[index - 1].node.pageAttributes.slug
const nextArticle = index === articles.length - 1 ? null : articles[index + 1].node.pageAttributes.slug
createPage({
slug,
component: blogArticleTemplate,
context: {
slug: slug,
previousArticle,
nextArticle,
},
})
})
}
但是,这个代码不起作用。返回以下错误。
error "gatsby-node.js" threw an error while running the createPages lifecycle:
Cannot read property 'slug' of undefined
33 | articles.forEach(( node, index ) => {
> 34 | const slug = node.pageAttributes.slug
| ^
35 | const previousArticle = index === 0 ? null : articles[index - 1].node.pageAttributes.slug
36 | const nextArticle = index === articles.length - 1 ? null : articles[index + 1].node.pageAttributes.slug
37 |
错误消息显示pageAttributes
未定义,但我已确认pageAttributes
未定义。
将console.log(node(插入到我的代码中,您可以看到pageAttributes的存在,正如您所看到的。
[Object: null prototype] {
node: [Object: null prototype] {
pageAttributes: [Object: null prototype] { slug: '/test' }
}
}
所以,我有两个问题:
- 这个问题的解决方案是什么
- 为什么我会出现这样的错误
谢谢。
您访问了错误的嵌套可迭代对象。您已经定义了articles
,但当对它们进行迭代时,node
不是嵌套对象,只是文章本身,可迭代对象。你需要降低一个级别。
将循环更改为:
articles.forEach(({ node } ) => {
const slug = node.pageAttributes.slug
// rest of the code
}
使用上面的代码片段,您将对可迭代对象(文章(进行解构,以获得node
本身。或者,如果你想保留以前的结构,只需访问:
articles.forEach(( node, index ) => {
const slug = node.node.pageAttributes.slug
// rest of the code
}
在这种情况下,我建议将命名更改为:
articles.forEach(( article, index ) => {
const slug = article.node.pageAttributes.slug
// rest of the code
}