【问题标题】:How do you pass variables to pageQuery如何将变量传递给 pageQuery
【发布时间】:2018-03-04 01:29:13
【问题描述】:

我在 Gatsby 中有这个页面:

import React from 'react'
import Link from 'gatsby-link'

import IntroPartial from '../partials/themes/intro'

export default class ThemeTemplate extends React.Component {
  render(){
    const theme = this.props.pathContext.theme
    console.dir(this.data)
    return (
      <div>
        <h1>{theme.name}</h1>
        <IntroPartial theme={theme} />
      </div>
    )
  }
}

export const pageQuery = graphql`
query ThemeQuery($theme: String){
  allMarkdownRemark(
    filter: { frontmatter: { themes: { in: [$theme] } } }
  ){
    edges{
      node{
        frontmatter{
          title
          themes
        }
        html
      }
    }
  }
}
`

假设我为$theme 提供了一个选项,此查询在 GraphQL 测试器中运行良好。如何提供$theme 的值?我想将其设置为this.props.pathContext.theme.slug

文档似乎暗示某些变量应该可以正常工作,但我不确定如何添加我自己的。

【问题讨论】:

    标签: gatsby


    【解决方案1】:

    传入graphql的变量来自createPage。它通常在您的 gatsby-node 文件中调用。您经常会在需要的示例中看到使用的路径,如 $path。

    为了包含您自己的附加变量以传递给 graphql 调用,您需要将它们添加到上下文中。稍微修改一下文档中的示例:

    createPage({
      path: `/my-sweet-new-page/`,
      component: path.resolve(`./src/templates/my-sweet-new-page.js`),
      // The context is passed as props to the component as well
      // as into the component's GraphQL query.
      context: {
       theme: `name of your theme`,
     },
    })
    

    然后您可以像在示例中一样在查询中使用 $theme。在上面的代码中设置 $theme 将在 createPages 部分完成(参见示例),因为您将可以访问所有数据。

    【讨论】:

    • 不得不说组件中的graphqlgatsby中最大的黑盒。如果不是你,我永远不会知道graphql variable 来自createPage,尽管它在文档中。
    • 这有什么不可行的原因吗?我正在使用相同的代码,但过滤器在页面上不起作用,但在 gql 浏览器中起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2018-12-28
    • 2011-04-12
    • 2017-01-24
    • 2018-05-17
    • 2012-04-20
    • 1970-01-01
    相关资源
    最近更新 更多