首页 > 解决方案 > GatsbyJS - 向 graphQL 添加变量

问题描述

我正在构建一个动态 gatsby 应用程序,用户可以在其中登录并查看类别列表,以及每个类别的产品列表。当用户点击一个类别时,我想通过 graphQL 查询动态呈现相关产品。我想如何做到这一点是通过从 URL 中获取类别 slug 并将其传递给 graphQL 查询,但是当我传递变量时我不断收到错误。

我在下面粘贴了我的查询,没有变量。我想要一个变量 ${slug} 而不是“无服务器”。

export const query = graphql`
{ 
    fauna {
        slugMap (slug: "serverless"){
                data{
            name
            companies{
            data{
                name
                website
                description
            }
            }
        }

        }
  }
}
`

Gatsby-node.js

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions
  // Only update the `/app` page.
  if (page.path.match(/^\/map/)) {
    // page.matchPath is a special key that's used for matching pages
    // with corresponding routes only on the client.
    page.matchPath = "/map/*"
    // Update the page.
    createPage(page)
  }
}

标签: javascriptreactjsgraphqlgatsby

解决方案


Gatsby 查询用于在开发或构建过程中查询内部状态- 在部署后它不活动(不存在)。

对于动态查询,您需要活动/实时数据源- 一些 graphql 服务器。您可以使用 graphql 客户端 (fe apollo) 或fetch(POST jsongraphql requests)。这在 gatsby dosc - data-fetching中有解释


推荐阅读