如何将变量传递给pageQuery

时间:2017-09-22 12:48:29

标签: gatsby

我在盖茨比有这个页面:

xvBv49PpaYvXAIfy3iOSDWNQj89iZWlqaW5n

此查询在GraphQL测试器中正常工作,假设我为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提供价值?我想将其设置为$theme

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

1 个答案:

答案 0 :(得分:22)

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

相关问题