reactjs - 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 查询?
解决方案
这个问题是Gatsby 的一个已知限制,useStaticQuery
而不是 GraphQL 本身。
GraphQL 明确定义了在查询中使用变量的方法。这需要以下 3 个步骤:
- 将其中的静态值替换
query
为$variableName
- 声明
$variableName
为接受的变量之一query
- 传入
variableName: value
单独的、特定于传输的(通常是 JSON)变量字典
在您的情况下,我建议在传递给useStaticQuery()
函数之前获取参数并使用字符串插值来创建查询
推荐阅读
- service - Ingress-Nginx-Controller 找不到部署在 Google Cloud Platform 上的第二个服务
- javascript - Onsubmit 事件拒绝触发
- android - Apollo Android 中的多个模式
- exec - ptracing 修补 linux 内核失败
- c# - C# wpf Process.start 没有断点将无法工作
- python - 生成 Gillespie 模型仿真
- python - 曲线拟合点列表
- algorithm - 使用 Union Find 查找无向图中的连通分量数
- python - 尝试构建 BeautifulSoup 以灵活地抓取公司年报
- flutter - 在 setState 中使用异步操作的解决方法