在gatsbyjs中以编程方式创建页面时,如何解决“ TypeError:无法读取未定义的属性'node'”

时间:2019-04-27 03:02:40

标签: javascript node.js reactjs gatsby

我正在尝试使用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”功能所示。

1 个答案:

答案 0 :(得分:2)

您的代码存在问题,即您试图访问数组等对象

const previous= index === post.length-1?null: post[index+1].node
const next= index === 0?null: post[index-1].node

在上面的代码中,post是单个对象。 i: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将引发错误。