我正在尝试使用gatsbyjs创建一个博客,并希望以编程方式创建我的博客页面,而不是在/ src / pages文件夹中显式创建它们。
我目前正在尝试从内容中查询数据,我根据GraphiQL成功完成了这项工作。我大部分都遵循了文档中提供的步骤,但每当我的程序进入“.forEach”函数时,我都会遇到此错误。
exports.createPages=({graphql,actions})=>{
const {createPage}=actions
const blogPost= path.resolve('./src/components/blogComponents/blog-post.js')
return new Promise((resolve,reject)=>{
graphql(`
{
allContentfulBlog{
edges{
node{
slug
}
}
}
}
`).then(results=>{
// console.log(results)
if(results.error){
reject(results.error)
}
// create blog post pages
const posts=results.data.allContentfulBlog.edges
console.log(post)
posts.forEach((post,index)=>{
console.log(`showing slugs: ${posts.node.slug}`)
const previous= index === posts.length-1?null: post[index+1].node
const next= index === 0?null: posts[index-1].node
createPage({
path:post.node.slug,
component:blogPost ,
context:{
slug:post.node.slug,
previous,
next
}
})
})
}).then(resolve)
})
这是返回结果的模式
"data": {
"allContentfulBlog": {
"edges": [
{
"node": {
"slug": "web-developer-roadmap"
}
},
{
"node": {
"slug": "web-fundamentals-1"
}
}
]
}
}
我希望“forEach”函数循环遍历我的所有博客,并为“createPage”函数分配适当的值,但相反,它会继续显示告诉我查询中可用的节点属性未定义,即使我确认其存在通过将其记录到控制台,如“forEach”功能中所示。
你的代码问题是你试图像数组一样访问对象
const previous= index === post.length-1?null: post[index+1].node
const next= index === 0?null: post[index-1].node
在上面的代码中,post
是单个对象。我:e { node: {} }
,你正在访问它像一个阵列post[index+1].node
。
const posts =[
{
node: {
slug: "lorem"
}
},
{
node: {
slug: "ipsum"
}
}
];
posts.forEach((post, i) => {
// post is a single object. To access it's node, you need to use post.node
console.log("current post", post);
// To access the next post based on index
if(i<posts.length-1) {
console.log("Next node", posts[i + 1].node);
}
});
如果您想根据索引迭代下一篇文章,请使用posts[index-1].node
。同时确保检查索引,因为对于最后一个元素,index+1
将抛出错误。