【问题标题】:Does Gatsby's createPages API send the path to the template?Gatsby 的 createPages API 是否将路径发送到模板?
【发布时间】:2020-08-24 07:52:32
【问题描述】:

我一直在关注这个 Gatsby 教程,根据我的 CMS 创建的 Markdown 文件动态创建页面:https://www.gatsbyjs.org/docs/adding-markdown-pages/

我不明白 blogTemplate.js 文件中的 GraphQL 查询如何接收 $path 变量。我可以看到 gatsby-node.js 中的 createPages 函数根据其自己的 GraphQL 查询的结果创建页面,并使用 'path' frontmatter 元素为创建的页面选择 URL。

但是,创建的页面如何知道自己的路径?教程中名为 pageQuery 的查询使用 $path 变量来获取自己的数据,但我看不到它是如何接收该变量的。提前感谢您的任何解释。

【问题讨论】:

    标签: reactjs graphql gatsby


    【解决方案1】:

    在创建页面时,我们可以传递上下文, All context values are made available to a template’s GraphQL queries as arguments prefaced with $

         exports.createPages = async function ({ actions, graphql }) {
      const { data } = await graphql(`
        query {
          allMarkdownRemark {
            edges {
              node {
                fields {
                  slug
                }
              }
            }
          }
        }
      `)
      data.allMarkdownRemark.edges.forEach(edge => {
        const slug = edge.node.fields.slug
        actions.createPage({
          path: slug,
          component: require.resolve(`./src/templates/blog-post.js`),
          context: { path: slug }, //here you can pass path through context parameter, the slug can be then accesed under $path variable in the template
        })
      })
    }
    `
    

    使用 $ 符号我们可以在模板端访问路径值

      export const query = graphql`
      query($path: String!) {
        ...
      }
    `
    

    【讨论】:

    • 感谢您到目前为止的帮助:我了解 gatsby-node.js createPages 函数使用您编写的查询,但我的问题是关于 blogTemplate.js 文件上的查询。该查询(在文档中称为“pageQuery”)如何获取 $page 变量?
    • 为此,我会发布一个答案
    【解决方案2】:

    Graphql 在内部使用 redux,所有关于页面创建和路径的信息都会更新到 gatsby 的 redux 存储中,然后从那里为每个页面执行 graphql 查询

    现在根据gatsby createPage github code comment

    “上下文”中的数据在以下情况下作为潜在参数传递给 GraphQL 运行页面查询。

    GraphQL 的参数被构造时,context 对象是 与页面对象相结合,因此 both 页面对象和上下文数据 可用作参数。所以你不需要添加页面“path” 到上下文,因为它已经在 GraphQL 中可用。如果一个上下文 字段复制页面对象已使用的字段,这可以 在 Gatsby 中破坏功能,所以必须避免。

    【讨论】:

      猜你喜欢
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 2018-08-25
      • 2018-03-31
      • 2017-09-03
      • 1970-01-01
      相关资源
      最近更新 更多