【问题标题】:GraphQL - Gatsby.js- React component. - How to query with variables/arguments?GraphQL - Gatsby.js- React 组件。 - 如何查询变量/参数?
【发布时间】:2020-06-20 13:01:53
【问题描述】:

我有一个需要查询数据的 React 组件。我想将参数/变量传递给查询。但我不知道该怎么做。

例如。我有这个博客项目轮播,它想要查询 x 数量的项目和 x 数量的偏移量(跳过第一个 x 数字)。

这大概是我现在所拥有的。但我不知道如何在 GraphQL 查询中传递变量

import React from "react"
import {graphql, useStaticQuery} from "gatsby";
import BlockCarousel from "../blockCarousel/blockCarousel";


const BlockCarouselBlog = ({block,data}) => {

  let queryArgs = {
    limit: 10,
    skip: 0
  };
  
  block.blocks = GetBlogItems(queryArgs);

  return (
    <BlockCarousel block={block} data={data} />
  )
};
export default BlockCarouselBlog



const GetBlogItems = (args) => {

    let data = useStaticQuery(graphql`
      query {
        allSanityBlog(
          sort: { fields: [_createdAt], order: DESC }
          limit: 10 // this needs the variable
          skip: 0 // this needs the variable
        ) {
          ... rest of the data
        }


      }
    `)

    if (data.allSanityBlog.edges)
      return data.allSanityBlog.edges

    return null;
  }

问题

如何将参数传递到 Gatsby GraphQL 查询组件

【问题讨论】:

标签: reactjs graphql gatsby react-component sanity


【解决方案1】:

这个问题是Known limitation of Gatsby's useStaticQuery 而不是 GraphQL 本身。

GraphQL clearly defines a way to use variables in a query。这需要以下 3 个步骤:

  1. query 中的静态值替换为$variableName
  2. $variableName 声明为query 接受的变量之一
  3. 在单独的、特定于传输的(通常是 JSON)变量字典中传递 variableName: value

在您的情况下,我建议在传递给 useStaticQuery() 函数之前获取参数并使用字符串插值来创建查询

【讨论】:

  • Arg... 稍微说一下,很糟糕... 但这会使它变得非常不灵活。我在看你的字符串插值。您的意思是将其更改为类似 limit: ${args.limit} 的行吗?因为这会给我一个错误:BabelPluginRemoveGraphQLQueries: String interpolations are not allowed in graphql fragments
猜你喜欢
  • 2021-05-28
  • 2019-06-18
  • 2019-02-20
  • 2019-12-03
  • 2020-01-22
  • 2019-11-28
  • 2019-06-22
  • 2017-04-22
  • 2019-01-26
相关资源
最近更新 更多