React中使用GraphQL查询嵌套对象返回undefined问题求助
问题排查原因
useQuery未传递必填参数:你定义的GraphQL查询声明了必填入参$userId: ID!,但调用useQuery时没有传入variables配置携带userId值,导致查询请求缺少必要参数,后端无法返回正确数据。- 字段大小写不匹配:GraphQL查询中定义返回的嵌套字段为
createdEvents(小写字母c开头),但前端代码中读取的是CreatedEvents(大写字母C开头),字段名不匹配导致读取结果为undefined。 - 变量命名逻辑错误:你将查询返回的用户对象
getUserPost重命名为userId,语义完全不符,容易引发后续逻辑混淆。 - 导入语法错误:
graphql-tag的导入语句缺少引号,会导致模块导入失败。
修复方案
1. 修复模块导入
// 补充导入语句的引号 import gql from 'graphql-tag'
2. 调用useQuery时传入必填参数
先从你的登录状态存储位置(如localStorage、全局状态、上下文等)获取当前登录用户的userId,调用useQuery时传入variables配置:
export default function Dashboard() { // 替换为你实际获取当前登录用户userId的逻辑 const currentUserId = localStorage.getItem('loginUserId') const { loading, data } = useQuery(FETCH_POST_QUERY, { variables: { userId: currentUserId } }); // 增加空值兜底判断 if (loading) return <div>Loading...</div>; if (!data?.getUserPost) return <div>暂无发布的活动</div>; // 语义化命名返回的用户对象 const { getUserPost: currentUser } = data; return ( <div className="PostCard"> <h1>Host Events</h1> {/* 使用正确的小写开头字段名,增加可选链避免空值报错 */} {currentUser?.createdEvents.map((list) => ( <PostCard id={list.id} key={list.id} title={list.title} description={list.description} price={list.price} address={list.address} date={list.date} /> ))} </div> ); }
内容的提问来源于stack exchange,提问作者Kug
相关产品推荐
相关产品推荐

