在Gatsby中的JSX组件外部进行graphql查询 [英] Make graphql query outside a JSX component in Gatsby
问题描述
我有一个.ts
(不是.tsx
)文件,该文件仅导出json对象,如
I have a .ts
(not .tsx
) file which just exports a json object like
const obj = {
img1: gql_img1,
img2: gql_img2
}
我希望gq1_img1
和gq1_img2
成为graphql查询的结果
I want gq1_img1
and gq1_img2
to be the results of a graphql query
我找到了一个使用Apollo的解决方案客户端,但看起来他们并没有使用盖茨比,而且我也不认为盖茨比使用了客户端.
I found a solution which uses Apollo Client, but it doesn't look like they're using Gatsby and I don't think Gatsby uses a client.
使用useStaticQuery
的问题是它是一个钩子,如果我尝试像下面的代码片段一样使用它,则会得到"Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:"
The problem with using useStaticQuery
is that it's a hook, if I try to use it like in the snippet below, I get "Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:"
const gql = () => {
const gql = useStaticQuery(graphql
`query adQuery {
invoiceNinja300x250: file(
extension: {regex: "/(jpg)|(jpeg)|(png)/"},
name: {eq: "IN-300x250-2"}
){
childImageSharp {
fluid(maxWidth: 250) {
...GatsbyImageSharpFluid_withWebp_noBase64
}
}
},
invoiceNinja600x300: file(
extension: {regex: "/(jpg)|(jpeg)|(png)/"},
name: {eq: "IN-600x300-2"}
){
childImageSharp {
fluid(maxWidth: 250) {
...GatsbyImageSharpFluid_withWebp_noBase64
}
}
}
}`
)
return gql
}
const GQL = gql()
推荐答案
您是否考虑过React Context API?在生产型Gatsby应用程序上,我致力于将其用于全局变量(如一些JSON/对象数据).它允许您在某种高级/布局/数据层组件中,将从其他文件中获得的某些值填充到您的应用中,以与其他组件一起使用.
Have you considered the React Context API? On the production Gatsby app I work on that's what we use for global variables like some JSON/object data. It allows you in some sort of high level/layout/data layer component to stuff some values you get from a different file into your app to use with other components.
这篇关于在Gatsby中的JSX组件外部进行graphql查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!