【问题标题】:GatsbyJS passing user input to GraphQLGatsbyJS 将用户输入传递给 GraphQL
【发布时间】:2019-12-08 01:41:14
【问题描述】:

我正在寻找有关在 GatsbyJS 中接受来自表单的用户输入并将其传递给我的 GraphQL 查询的示例/教程。

我可以在提交时获取用户输入,也可以在测试 graphiql 时传入变量,我只是不知道如何将两者结合起来。

我的数据存储在 Drupal 中,是一个食谱列表。

我希望用户能够输入成分,例如鸡肉,然后检索以鸡肉为原料的所有食谱。

我的查询是

query SearchPageQuery($ingredient: String) {
  allNodeRecipes(filter: {relationships: {field_ingredients: {elemMatch: {title: {eq: $ingredient}}}}}) {
    edges {
      node {
        id
        title
        path {
          alias
        }
        relationships {
          field_ingredients {
            title
          }
        }
      }
    }
  }
}

【问题讨论】:

  • 你到底想用这个变量做什么?
  • @ksav 我已经更详细地更新了这个问题
  • 这听起来像是你想要一个搜索功能。你见过github.com/humanseelabs/gatsby-plugin-lunr 吗?
  • 谢谢推荐,我去看看

标签: graphql gatsby


【解决方案1】:

如果我正确理解您的问题,简短的回答是您不能,但另一种方法可能对您有用。

Gatsby 的 GraphQL 查询作为站点静态构建的一部分预先运行,因此数据是客户端 JavaScript 的一部分,但此时查询已经运行。

这与您不能在 StaticQuery 中使用 JavaScript 模板文字的原因相同:

// This doesn’t work
let myDynamicSlug = 'home'

return (
  <StaticQuery
    query={graphql`
query ExampleQuery {
  examplePage(slug: { eq: ${myDynamicSlug} }) {
    title
  }
}
`}
    render={data => {
      console.log(data)
    }}
  />
)

您将收到一条错误消息,解释“graphql 片段中不允许字符串插值”。延伸阅读:https://github.com/gatsbyjs/gatsby/issues/2293

我最近遇到了类似的问题,我意识到为什么你不能这样做是有道理的。如果你是,前。使用 GraphQL 中的查询和类似的东西生成图像,您不能传入客户端变量,因为到那时,所有“静态站点”Gatsby 操作(如处理图像)都已经完成。

对我有用的是在查询中获取我需要的大部分数据,并在其中找到我需要的内容。在我之前的示例中,这可能意味着获取allExamplePages 而不是一个examplePage,然后在其中找到我需要的myDynamicSlug

// This isn’t exactly how you’d hope to be able to do it,
// but it does work for certain problems
let myDynamicSlug = 'home'

return (
  <StaticQuery
    query={graphql`
query ExampleQuery {
  # You might still be able to limit this query, ex. if you know your item
  # is within the last 10 items or you don’t need any items before a certain date,
  # but if not you might need to query everything
  allExamplePages() {
    edges {
      node {
        title
        slug
      }
    }
  }
}
`}
    render={data => {
      // Find and use the item you want, however is appropriate here
      data.edges.forEach(item => {
        if (item.node.slug === myDynamicSlug) {
          console.log(item)
        }
      })
    }}
  />
)

在您的情况下,希望有一个等价物,例如。根据用户输入查找内容。如果您可以更具体地了解您的数据结构,我很乐意尝试让我的建议更具体。希望对您有所帮助!

【讨论】:

  • 我已经编辑了我的问题以包含更多细节。感谢您的详细回复。
  • 我同意其他评论,听起来你可能想要一个搜索插件。要么得到 allNodeRecipes 而没有任何过滤器,然后手动执行过滤或排序客户端。另一种选择是,如果您可以从前端使用 Drupal API 端点进行搜索,然后获得您需要的响应。
猜你喜欢
  • 2020-08-12
  • 2019-01-04
  • 2019-05-24
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
相关资源
最近更新 更多