如何将变量传递给pageQuery

阿卡斯

我在盖茨比有此页面:

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
      }
    }
  }
}
`

假设我向提供了一个选项,则该查询在GraphQL测试仪中可以正常工作$theme我该如何提供价值$theme我想将其设置为this.props.pathContext.theme.slug

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

马克·米雄

传递到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部分中完成(请参见示例),因为您随后将可以访问所有数据。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章