2

我正在使用 Gatsby/Netlify CMS 堆栈,并一直在尝试在主页上显示 markdown 文件内容。例如,我在 src/pages/experience 中有一个目录,其中显示了所有体验降价文件。

所以使用graphql,我有一个实际有效的查询:

{
        allMarkdownRemark(
         limit: 3,
         sort: { order: DESC, fields: [frontmatter___date] },
         filter: { fileAbsolutePath: { regex: "/(experience)/" } }
       ) {
           edges {
             node {
               id
               frontmatter {
                 title
                 company_role
                 location
                 work_from
                 work_to
                 tags
               }
               excerpt
             }
           }
         }
     }

但是,在我的组件页面上运行它时,它显示 × TypeError: Cannot read property 'allMarkdownRemark' of undefined

但是,在返回之前输入此内容后:

if (!data) { return null };

错误消失了,但整个部分都消失了。下面是:

const Experience = ({data}) => {

return (

    <div id="experience" className="section accent">
              <div className="w-container">
                  <div className="section-title-group">
                    <Link to="#experience"><h2 className="section-heading centered">Experience</h2></Link>
                  </div>
              <div className="columns w-row">
                     {data.allMarkdownRemark.edges.map(({node}) => (
                        <div className="column-2 w-col w-col-4 w-col-stack" key={node.id}>
                            <div className="text-block"><strong>{node.frontmatter.title}</strong></div>
                            <div className="text-block-4">{node.frontmatter.company_role}</div>
                            <div className="text-block-4">{node.frontmatter.location}</div>
                            <div className="text-block-3">{node.frontmatter.work_from} – {node.frontmatter.work_to}</div>
                            <p className="paragraph">{node.frontmatter.excerpt}</p>
                            <div className="skill-div">{node.frontmatter.tags}</div>
                        </div>
                     ))} 
              </div>
          </div>
      </div>
)}

export default Experience

在 gatsby-config-js 中,我添加了一个独立于 /src/posts 的 gatsby-source-filesystem 解析到 /src/pages,其中体验目录是 src/pages/experience。

更新:2/7/2019 这是 gatsby-config-js 文件:

module.exports = {
  siteMetadata: {
    title: `Howard Tibbs Portfolio`,
    description: `This is a barebones template for my portfolio site`,
    author: `Howard Tibbs III`,
    createdAt: 2019
  },
    plugins: [
      `gatsby-plugin-react-helmet`,
      {
        resolve: `gatsby-source-filesystem`,
        options: {
          name: `images`,
          path: `${__dirname}/src/images`,
          },
      },
      {
        resolve: 'gatsby-transformer-remark',
        options: {
          plugins: [
            {
              resolve: 'gatsby-remark-images',
            },
          ],
        },
      },
      {
        resolve: `gatsby-source-filesystem`,
        options: {
          name: `posts`,
          path: `${__dirname}/src/posts`,
          },
      },
      {
        resolve: `gatsby-source-filesystem`,
        options: {
          name: `pages`,
          path: `${__dirname}/src/pages`,
          },
      },
        `gatsby-plugin-netlify-cms`,
        `gatsby-plugin-sharp`,
        {
          resolve: `gatsby-plugin-manifest`,
          options: {
            name: `gatsby-starter-default`,
            short_name: `starter`,
            start_url: `/`,
            background_color: `#663399`,
            theme_color: `#663399`,
            display: `minimal-ui`,
            icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
          },
        },
        `gatsby-transformer-sharp`
    ],
  }

我的感觉是,在 gatsby-node-js 的某个地方,我没有创建一个实例来处理该类型的查询。

const path = require('path')
const { createFilePath } = require('gatsby-source-filesystem')

const PostTemplate = path.resolve('./src/templates/post-template.js')
const BlogTemplate = path.resolve('./src/templates/blog-template.js')

exports.onCreateNode = ({ node, getNode, actions }) => {
    const { createNodeField } = actions
    if (node.internal.type === 'MarkdownRemark') {
        const slug = createFilePath({ node, getNode, basePath: 'posts' })
    createNodeField({
        node,
        name: 'slug',
        value: slug,
    })

}
}

exports.createPages = async ({ graphql, actions }) => {

const { createPage } = actions
const result = await graphql(`
    {
        allMarkdownRemark (limit: 1000) {
          edges {
            node {
              fields {
                slug
              }

            }
          }
        }
      }
`)

const posts = result.data.allMarkdownRemark.edges

posts.forEach(({ node: post }) => {
    createPage({
        path: `posts${post.fields.slug}`,
        component: PostTemplate,
        context: {
            slug: post.fields.slug,
        },
    })
})

const postsPerPage = 2
const totalPages = Math.ceil(posts.length / postsPerPage)

Array.from({ length: totalPages }).forEach((_, index) => {
    const currentPage = index + 1
    const isFirstPage = index === 0
    const isLastPage = currentPage === totalPages

    createPage({
        path: isFirstPage ? '/blog' : `/blog/${currentPage}`,
        component: BlogTemplate,
        context: {
            limit: postsPerPage,
            skip: index * postsPerPage,
            isFirstPage,
            isLastPage,
            currentPage,
            totalPages,
        },
    })
})
}

想知道是否有人能够得到类似工作的东西?非常感谢您的帮助。


更新:2019 年 2 月 6 日

所以对我的代码从 pageQuery 到 StaticQuery 进行了一些更改,不幸的是它仍然不起作用,但我相信它正朝着正确的方向发展:

export default() => (

    <div id="experience" className="section accent">
              <div className="w-container">
                  <div className="section-title-group">
                    <Link to="#experience"><h2 className="section-heading centered">Experience</h2></Link>
                  </div>
              <div className="columns w-row">
              <StaticQuery
              query={graphql`
                  query ExperienceQuery {
                      allMarkdownRemark(
                       limit: 2,
                       sort: { order: DESC, fields: [frontmatter___date]},
                       filter: {fileAbsolutePath: {regex: "/(experience)/"}}
                     ) {
                         edges {
                           node {
                             id
                             frontmatter {
                               title
                               company_role
                               location
                               work_from
                               work_to
                               tags
                             }
                             excerpt
                           }
                         }
                       }
                   }

              `}
              render={data => (
                  <div className="column-2 w-col w-col-4 w-col-stack" key={data.allMarkdownRemark.id}>
                  <div className="text-block"><strong>{data.allMarkdownRemark.frontmatter.title}</strong></div>
                  <div className="text-block-4">{data.allMarkdownRemark.frontmatter.company_role}</div>
                  <div className="text-block-4">{data.allMarkdownRemark.frontmatter.location}</div>
                  <div className="text-block-3">{data.allMarkdownRemark.frontmatter.work_from} – {data.allMarkdownRemark.frontmatter.work_to}</div>
                  <p className="paragraph">{data.allMarkdownRemark.frontmatter.excerpt}</p>
                  <div className="skill-div">{data.allMarkdownRemark.frontmatter.tags}</div>
                  </div>
              )}
              />
              </div>
          </div>
      </div>
);

我收到此错误 TypeError: Cannot read property 'title' of undefined

所以我想要完成的是本节中的这个实例。当然这是一个占位符,但我希望用每个降价的内容替换该占位符。 体验剪辑


更新:2019 年 2 月 7 日

所以今天没有变化,但想发布一些字段,以便更好地了解我正在尝试做的事情。这是来自 NetlifyCMS 的 config.yml 文件,它在其中显示集合。这就是我正在完成的(注意:测试 repo 只是为了查看实际的 CMS,我会寻求改变):

backend:
  name: test-repo
  branch: master

media_folder: static/images
public_folder: /images

display_url: https://gatsby-netlify-cms-example.netlify.com/

# This line should *not* be indented
publish_mode: editorial_workflow

collections:

  - name: "experience"
    label: "Experience"
    folder: "experience"
    create: true
    fields:
        - { name: "title", label: "Company Title", widget: "string" }
        - { name: "company_role", label: "Position Title", widget: "string" }
        - { name: "location", label: "Location", widget: "string" }
        - { name: "work_from", label: "From", widget: "date", format: "MMM YYYY" }
        - { name: "work_to", label: "To", default: "Present", widget: "date", format: "MMM YYYY" }
        - { name: "description", label: "Description", widget: "text" }
        - { name: "tags", label: "Skills Tags", widget: "select", multiple: "true", 
              options: ["ReactJS", "NodeJS", "HTML", "CSS", "Sass", "PHP", "Typescript", "Joomla", "CMS Made Simple"] }


  - name: "blog"
    label: "Blog"
    folder: "blog"
    create: true
    slug: "{{year}}-{{month}}-{{day}}_{{slug}}"
    fields:
      - { name: path, label: Path }
      - { label: "Image", name: "image", widget: "image" }
      - { name: title, label: Title }
      - { label: "Publish Date", name: "date", widget: "datetime" }
      - {label: "Category", name: "category", widget: "string"}
      - { name: "body", label: "body", widget: markdown }
      - { name: tags, label: Tags, widget: list }


  - name: "projects"
    label: "Projects"
    folder: "projects"
    create: true
    fields:
      - { name: date, label: Date, widget: date }
      - {label: "Category", name: "category", widget: "string"}
      - { name: title, label: Title }
      - { label: "Image", name: "image", widget: "image" }
      - { label: "Description", name: "description", widget: "text" }
      - { name: body, label: "Details", widget: markdown }
      - { name: tags, label: Tags, widget: list}


  - name: "about"
    label: "About"
    folder: "src/pages/about"
    create: false
    slug: "{{slug}}"
    fields:
      - {
          label: "Content Type",
          name: "contentType",
          widget: "hidden",
          default: "about",
        }
      - { label: "Path", name: "path", widget: "hidden", default: "/about" }
      - { label: "Title", name: "title", widget: "string" }
      - { label: "Body", name: "body", widget: "markdown" }

对于降价页面的示例,这将是在体验部分中查找的格式,因为正如您在图片中看到的那样,它显示在整个容器中:

---
title: Test Company
company_role: Test Role
location: Anytown, USA
work_from: January, 2020
work_to: January, 2020
tags: Test, Customer Service
---

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

更新:2019 年 2 月 8 日

我确实对下面提供的代码进行了一些更新,但在我开始之前,这里有一些我想要完成的图像。这些是我希望替换为真实数据的占位符。这是针对每个部分的:

完整体验截图

项目截图

博客截图

我已经运行了@staypuftman 在下面的答案中提供的代码,并出现了这个错误:

您网站的“gatsby-node.js”创建了一个页面,其中包含一个不存在的组件。

除了已经存在的代码之外,我还添加了代码并处理了该错误。这就是我最初认为会发生的事情,也是我想独立使用 StaticQuery 的原因。这实际上是我在文档和入门存储库中遇到的主要问题,没有人真正在 node.js 中创建多个变量。

我还尝试了来自@DerekNguyen 的修订版,看起来像这样:

import React from "react"
import { Link, graphql, StaticQuery } from "gatsby"



export default(data) => (

        <div id="experience" className="section accent">
                  <div className="w-container">
                      <div className="section-title-group">
                        <Link to="#experience"><h2 className="section-heading centered">Experience</h2></Link>
                      </div>
                  <div className="columns w-row">
                  <StaticQuery
                  query={graphql`
                      query ExperienceQuery {
                          allMarkdownRemark(
                           limit: 2,
                           sort: { order: DESC, fields: [frontmatter___date]},
                           filter: {fileAbsolutePath: {regex: "/(experience)/"}}
                         ) {
                             edges {
                               node {
                                 id
                                 frontmatter {
                                   title
                                   company_role
                                   location
                                   work_from
                                   work_to
                                   tags
                                 }
                                 excerpt
                               }
                             }
                           }
                       }

                  `}
                  render={data.allMarkdownRemark.edges.map(({ node }) => (
                      <div className="column-2 w-col w-col-4 w-col-stack" key={node.id}>
                      <div className="text-block"><strong>{node.frontmatter.title}</strong></div>
                      <div className="text-block-4">{node.frontmatter.company_role}</div>
                      <div className="text-block-4">{node.frontmatter.location}</div>
                      <div className="text-block-3">{node.frontmatter.work_from} – {node.frontmatter.work_to}</div>
                      <p className="paragraph">{node.frontmatter.excerpt}</p>
                      <div className="skill-div">{node.frontmatter.tags}</div>
                      </div>
                  ))}
                  />
                  </div>
              </div>
          </div>
);

然而,这也带来了一个错误:

TypeError:无法读取未定义的属性“边缘”

仍在努力,但我认为它越来越接近解决方案。请记住,我还必须为其他变量创建它。


更新:2019 年 2 月 10 日

对于那些想看看我是如何使用 gatsby-starter 构建网站的人,这里是:

我的投资组合

4

1 回答 1

1

gastby-node.js当您有一堆需要位于的页面时使用/pages/{variable-here}/。Gatsby 用于gatsby-node.js针对您的数据源(在本例中为 Netlify CMS)运行 GraphQL 查询,并根据您的特定 GraphQL 查询获取所需的所有内容。

然后,它使用项目中的组件动态构建 X 个页面。它构建的页面数量取决于它在远程数据源中找到的内容。它们的外观取决于您指定的组件。在Gatsby 教程中了解更多信息。

Staticquery用于将一次性数据获取到组件中,而不是从数据源生成页面。它非常有用,但不是我认为您正在尝试做的事情。在Gatsby 网站上阅读更多相关信息。

基于所有这些以及您在上面提供的内容,我认为您gatsby-node.js应该看起来像这样:

// Give Node access to path
const path = require('path')

// Leverages node's createPages capabilities
exports.createPages = async ({ graphql, actions }) => {

  // Destructures createPage from redux actions, you'll use this in a minute
  const { createPage } = actions

  // Make your query
  const allExperiencePages = await graphql(`
    { 
      allMarkdownRemark(limit: 1000) {
        edges {
          node {
            id
            frontmatter {
              title
              company_role
              location
              work_from
              work_to
              tags
            }
            excerpt
          }  
        }
      }
    }
  `)

  // gatsby structures allExperiencePages into an object you can loop through
  // The documentation isn't great but the 'data' property contains what you're looking for
  // Run a forEach with a callback parameter that contains each page's data
  allExperiencePages.data.allMarkdownRemark.edges.forEach( page => {

    // Make individual pages with createPage variable you made earlier
    // The 'path' needs to match where you want the pages to be when your site builds
    // 'conponent' is what Gatsby will use to build the page
    // 'context' is the data that the component will receive when you `gatsby build`
    createPage({
      path: `/pages/${page.node.title}/`,
      component: path.resolve('src/components/Experience'),
      context: {
        id: page.node.id,
        title: page.node.frontmatter.title,
        company_role: page.node.frontmatter.company_role,
        location: page.node.frontmatter.location,
        work_from: page.node.frontmatter.work_from,
        work_to: page.node.frontmatter.work_to,
        tags: page.node.frontmatter.tags,
        excerpt: page.node.excerpt
      }
    })
  }) 

}

仅此一项可能不足以生成页面!这完全取决于您在文件的createPage组件部分中指定的组件的情况gatsby-node.js

于 2019-02-07T21:44:36.447 回答