【发布时间】:2021-03-28 07:10:06
【问题描述】:
我有点卡住了。我正在使用graphql-request 和react-query,跟随the example code quite closely。我用自己的后端替换了它,当我不使用变量但对值进行硬编码时它可以工作。它也适用于我的 GraphiQL 测试环境。
这样做很有效:
export default function usePost(postId) {
return useQuery(
["post", postId],
async () => {
const { post } = await request(
endpoint,
gql`
query {
post(id: "123123123123") { // <--- with the id hard-coded, it works
id
heading
content
}
}
`
)
return post
},
{
enabled: !!postId,
}
)
}
接下来是完全相同的代码,但现在之前硬编码的后置ID(“123123123123”)被替换为变量 em> (${postId})。就像described in the example code
export default function usePost(postId) {
return useQuery(
["post", postId],
async () => {
const { post } = await request(
endpoint,
gql`
query {
post(id: ${postId}) { // <--- with the ${postId} variable, things break, but it's exactly the same syntax as in the react-query example & it works in my graphiql backend. Also console-logged the postId, and it is correct
id
heading
content
}
}
`
)
return post
},
{
enabled: !!postId,
}
)
}
错误响应是:
commons.js:46154 错误:语法错误:预期:,找到): {"response":{"errors":[{"message":"语法错误:预期 :,找到 )","locations":[{"line":3,"column":46}]}],"status":400},"request":{"query":"\n 查询 {\n 帖子(id: 5fda109506038d9d18fa27e2) {\n
id\n 标题\n 内容\n }\n
}\n "}} 在 GraphQLClient。 (commons.js:13039) 在步骤 (commons.js:12930) 在 Object.next (commons.js:12911) 完成时 (commons.js:12902)
我猜是我弄错了一些语法?还是与现在缺少引号的事实有关?虽然示例代码也没有做任何不同的事情......真的不确定了,但实际上是一行打破了这一切,我无法弄清楚。
【问题讨论】:
标签: reactjs graphql react-hooks graphql-js react-query