React Next.js GraphQL查询:如何获取嵌套分类数据?
解决Next.js中GraphQL嵌套分类标题获取问题
1. 检查GraphQL查询是否包含嵌套字段
首先确保你的查询语句明确请求了Post_Category下的Categories_id.title(注意字段名大小写要和后端一致,GraphQL大小写敏感),示例查询:
query GetPosts { posts { title content Post_Category { Categories_id { title # 必须显式请求这个嵌套字段 } } } }
如果查询中遗漏这个字段,后端不会返回对应数据,自然无法获取。
2. 核对返回数据的嵌套结构
查看实际返回的JSON数据,确认Post_Category是数组还是单个对象:
- 如果是数组(比如一篇文章对应多个分类):
Post_Category是数组类型,需要遍历或取指定元素 - 如果是单个对象:直接通过层级访问
示例返回结构(数组情况):
{ "data": { "posts": [ { "title": "测试文章", "content": "文章内容", "Post_Category": [ { "Categories_id": { "title": "前端技术" } } ] } ] } }
3. 在组件中正确取值
根据数据结构,用对应路径访问嵌套字段,建议搭配可选链操作符?.避免空值报错:
export default function PostsPage({ posts }) { return ( <div> {posts.map(post => ( <article key={post.id}> <h2>{post.title}</h2> {/* 处理Post_Category为数组的情况,取第一个分类的标题 */} <p>分类:{post.Post_Category?.[0]?.Categories_id?.title}</p> <div dangerouslySetInnerHTML={{ __html: post.content }} /> </article> ))} </div> ) }
如果Post_Category是单个对象,直接写post.Post_Category?.Categories_id?.title即可。
内容的提问来源于stack exchange,提问作者Mayanktaker
相关产品推荐
相关产品推荐

