如何将变量传递给pageQuery

编程入门 行业动态 更新时间:2024-10-27 08:29:15
本文介绍了如何将变量传递给pageQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在盖茨比拥有此页面:

I have this page in 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.

This query works fine in the GraphQL tester assuming I supply an option to $theme. How do I provide the value for $theme? I'd like to set it to this.props.pathContext.theme.slug.

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

The docs seem to imply that some variables should just work, but I'm not sure how to add my own.

推荐答案

传递到graphql的变量来自 createPage .通常在您的gatsby-node文件中调用它.在必填示例中,您经常会看到路径用作$ path.

The variables passed into graphql are coming from createPage. It's normally called in your gatsby-node file. You'll often see path used, as $path, in examples as it is required.

为了包括自己的附加变量以传递到graphql调用中,您需要将它们添加到上下文中.从文档修改示例:

In order to include your own, additional variables to pass into the graphql call, you'll need to add them to context. Modifying the example from the docs a bit:

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 部分中完成(请参见该示例),这样您就可以访问所有数据.

You can then use $theme in the query as you have in your example. Setting $theme in the above code would be done in the createPages portion (see the example), as you'll then have access to all of the data.

更多推荐

如何将变量传递给pageQuery

本文发布于:2023-11-23 18:16:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622426.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何将   pageQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!