首页 > 解决方案 > GraphQL - Gatsby.js- React 组件。- 如何查询变量/参数?

问题描述

我有一个需要查询数据的 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 查询?

标签: reactjsgraphqlgatsbyreact-componentsanity

解决方案


这个问题是Gatsby 的一个已知限制,useStaticQuery而不是 GraphQL 本身。

GraphQL 明确定义了在查询中使用变量的方法。这需要以下 3 个步骤:

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

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


推荐阅读