【问题标题】:How to solve 'Cannot read property of undefined'如何解决“无法读取未定义的属性”
【发布时间】:2019-04-30 01:00:42
【问题描述】:

我正在使用基于 JS 的静态站点生成器 Gatsby,并且我正在尝试为每个类别创建一个页面,同时对同一页面进行分页。 这是我在 gatsby-node.js 中的代码,出现错误“无法读取未定义的属性 'kebabCase'”。

        let categories = []
        _.each(result.data.allMarkdownRemark.edges, edge => {
            if (_.get(edge, "node.frontmatter.categories")) {
                categories = categories.concat(edge.node.frontmatter.categories)
            }
        })

        const categoryarticles = result.data.allMarkdownRemark.edges
        const categoryarticlesPerPage = 6
        const numPages = Math.ceil(categoryarticles.length / categoryarticlesPerPage)

        Array.from({ length: numPages }).forEach((_, i) => {
            categories.forEach(category => {
                createPage({
                    path: i === 0 ? `/${_.kebabCase(category)}` : `/${_.kebabCase(category)}/${i + 1}`,
                    component: managementTemplate,
                    context: {
                        category,
                        limit: categoryarticlesPerPage,
                        skip: i * categoryarticlesPerPage,
                    },
                })
            })
        })

category 实际上是定义的,实际上当我创建类别页面而不尝试分页时,代码 categories.forEach(category ... ect 工作正常。 我错过了什么?

非常感谢。

【问题讨论】:

  • 那个错误并不是说category是未定义的。它说_ 未定义。
  • 哦,谢谢指出。我在文件的顶部定义了 const _ = require("lodash") ,所以不应该也定义它吗?

标签: javascript pagination graphql gatsby


【解决方案1】:

您的 Array#foreach 循环正在遮蔽 _,因此它不再引用 lodash。引用当前数组值,即undefined。

更改.forEach((_, i) 并使用不同的变量名,这样您就不会影响_。例如。 .forEach((el, i).

【讨论】:

    猜你喜欢
    • 2021-05-10
    • 2022-01-26
    • 2019-11-21
    • 2018-12-21
    • 2020-11-17
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    相关资源
    最近更新 更多