【问题标题】:Graphql query in Gatsby static query component with markdown fileGatsby 静态查询组件中的 Graphql 查询,带有 markdown 文件
【发布时间】:2019-06-12 00:47:24
【问题描述】:

我一直试图围绕这个问题思考一段时间,但无法解决。

总而言之,我正在尝试使用 netlify CMS 制作一个 Gatsby 网站。 CMS 的目的不是创建或删除页面,而是能够编辑不同静态页面的内容(即:关于、主页等...)

在我的 Gatsby 项目中,我基本上连接了我的 netlify CMS,我想要实现的文件结构大致如下:

myproject/
    |---src/
        |---CMS
            |---about.md
            |---index.md
        |---pages
            |---about.js
            |---index.js

可以从 CMS 编辑降价文件,我想在我的页面组件中使用这些数据。我使用 npm install 和相应的 gatsby-config.js 插件声明设置了 gatsby-markdown-remark 和 gatsby-source-filesystem。

这些降价将如下所示:

---
title: "About Page"
intro: "This is all about is"
---
We are doing this because we love it and we are good at it.

我希望能够通过静态查询提取这些数据以在页面组件中使用,但不知道如何定位。

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

    const IndexPage = () => (
      <StaticQuery
      query = { graphql`
        query IndexPageQuery {
          mardownRemark(frontmatter: {title: {eq:"About Page"}}) {
  frontmatter {
    title
    intro
  }
}      
        
      `} 

      render={data => (
        <h1>{data.markdownRemark.frontmatter.title</h1>
        <h2>{data.markdownRemark.frontmatter.intro}</h2>
      )}
      /> 
    )

    export default IndexPage


  

我试图尽量减少代码量,因为我真的认为我的问题来自 graphql 查询,但如果它让人感到困惑,我很抱歉。我也很困惑。

我们将不胜感激任何导致正确方向的帮助。可能是方法不是它应该如何工作。

谢谢。

【问题讨论】:

    标签: reactjs graphql markdown gatsby netlify-cms


    【解决方案1】:

    确保在您的gatsby-config 中,您已经像这样设置了gatsby-source-filesystem(它可以是一个新条目——您可以有多个gatsby-source-filesystem

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/CMS`, <-- your CMS folder
        name: `pages`, <-- will be your `sourceInstanceName` when you query `allFile`
      },
    },
    

    您的查询看起来不错。注意StaticQuery在你需要从组件中获取一些数据的时候很有用,但是在页面组件中,你可以使用普通的查询:

    import React from 'react'
    import { graphql } from 'gatsby'
    
    export default class Index extends React.Components {
      ...
    }
    
    export const pageQuery = graphql`
      query {
        markdownRemark(frontmatter: {
          title: {
            eq: "New Beginnings"
          }
        }) {
          id
          frontmatter {
            title
          }
        }
      }
    `
    

    如果这没有帮助,请告诉我!

    【讨论】:

    • 谢谢!我设法使用了您的解决方案。仍然不知道这样构建我的项目是否是最佳实践,但它确实有效;)
    • 嘿马克西姆!我通常看到./src/CMS 被用作自定义netlifyCMS(自定义小部件、css 等)的文件夹,并且内容相关文件存储在./content./data 中——不过我认为这并不重要!
    猜你喜欢
    • 2020-10-22
    • 2020-11-15
    • 2020-08-17
    • 2020-11-30
    • 1970-01-01
    • 2019-12-21
    • 2020-03-23
    • 2021-02-03
    • 2020-11-07
    相关资源
    最近更新 更多