指定Post ID获取单篇文章Cursor却返回全部——WPGraphQL问题
问题原因及解决方案
问题出在变量名称不匹配:
- 你的GraphQL查询定义的变量是
$id,但在useQuery中传递的变量键是postId,导致查询中的where: {id: $id}没有获取到有效值,过滤器失效,最终返回所有文章的cursor。
修复代码
修改React部分的变量传递,将postId对应到查询中的id变量:
let postId = 138 const postCursor = useQuery(GET_POST_CURSOR, {variables: {id: postId}}) if (!postCursor.loading) { console.log("cursor: ", postCursor) }
另外,建议在查询中给变量添加非空约束(如果业务逻辑中ID必填),避免类似未传值的问题:
export const GET_POST_CURSOR = gql ` query GetPostById($id: Int!) { posts(where: {id: $id}) { edges { cursor } } } `;
这样修改后,查询会正确根据指定的id筛选对应的文章,返回其cursor。
内容的提问来源于stack exchange,提问作者sash
相关产品推荐
相关产品推荐

