[英]GraphQL - Gatsby.js- React component. - How to query with variables/arguments?
I have a React Component that needs to query data.我有一个需要查询数据的 React 组件。 And I want to pass arguments/variables to the query.我想将参数/变量传递给查询。 But I don't know how to do that.但我不知道该怎么做。
For example.例如。 I have this blog item carousel that wants to query an x amount of items and an x amount of offset (skip first x number).我有这个博客项目轮播想要查询 x 数量的项目和 x 数量的偏移量(跳过第一个 x 数字)。
This is roughly what I have right now.这大概就是我现在所拥有的。 But I don't know how to pass the variables inside the GraphQL query但我不知道如何在 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;
}
How can I pass arguments into a Gatsby GraphQL query for a component ?如何将参数传递给组件的 Gatsby GraphQL 查询?
This problem is a Known limitation of Gatsby's useStaticQuery
and not with GraphQL itself.这个问题是Gatsby 的useStaticQuery
一个已知限制,而不是 GraphQL 本身。
GraphQL clearly defines a way to use variables in a query . GraphQL 明确定义了一种在查询中使用变量的方法。 This require below 3 steps:这需要以下 3 个步骤:
query
with $variableName
用$variableName
替换query
的静态值$variableName
as one of the variables accepted by the query
将$variableName
声明$variableName
query
接受的变量之一variableName: value
in the separate, transport-specific (usually JSON) variables dictionary传递variableName: value
单独的、特定于传输的(通常是 JSON)变量字典中的值In your case I would suggest to get the arguments and use string interpolation to create the query before passing to useStaticQuery()
function在您的情况下,我建议在传递给useStaticQuery()
函数之前获取参数并使用字符串插值来创建查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.