使用直接缓存访问时,如何获取Map中查询的返回值?
1. 使用直接缓存访问时,如何获取Map中的查询值?
从你第二个问题的代码来看,你应该是在用类似Apollo Client的GraphQL客户端吧?那直接访问缓存的话,官方推荐用client.readQuery()或者client.readFragment()来读取已缓存的查询结果,尽量别直接碰缓存底层的Map结构,避免搞乱缓存一致性。
如果你的查询返回结果里包含一个Map类型的字段,拿到缓存结果后直接用Map的get()方法取值就行;要是后端返回的是普通对象模拟的键值对(看起来像Map但其实是对象),用方括号或者点语法访问就好。举个实际的例子:
// 先定义好你的查询语句 const GET_TARGET_DATA = gql` query GetTargetData($incubatorId: ID!) { incubatorEvents(incubatorId: $incubatorId) { dateMap # 假设这是返回的Map类型字段 } } `; // 从缓存里读取已有的查询结果,变量要和之前查询时完全一致哦 const cachedData = this.props.client.readQuery({ query: GET_TARGET_DATA, variables: { incubatorId: this.currentUser.incubator._id } }); // 从Map里取特定键的值 const specificDateEvents = cachedData.incubatorEvents.dateMap.get("2024-05-20"); // 如果是普通对象的话,就这么写: // const specificDateEvents = cachedData.incubatorEvents.dateMap["2024-05-20"];
2. 批量查询代码中如何获取返回值
你现在的代码有个小问题:await直接跟着weekDates.map(...)是没用的,因为map()会返回一个Promise数组,但await不会自动等待数组里所有Promise完成。你得用Promise.all()把这个Promise数组包起来,这样才能等到所有查询都完成,拿到全部结果。
修改后的代码应该是这样的:
// 用Promise.all包裹map生成的Promise数组,等待所有查询完成 const allQueryResults = await Promise.all( weekDates.map(datee => this.props.client.query({ query: queryFetchAppEventsByDate, name: 'fetchAppEvents', variables: { incubatorId: this.currentUser.incubator._id, userId: this.props.getCurrentUser.currentUser._id, date: datee } }) ) ); // allQueryResults是一个数组,顺序和weekDates完全对应 // 如果你要把结果按日期整理成键值对,可以用reduce: const eventsByDate = weekDates.reduce((resultObj, date, index) => { resultObj[date] = allQueryResults[index].data; // 这里的data就是查询返回的核心数据 return resultObj; }, {}); // 或者直接遍历数组处理每个结果: allQueryResults.forEach((result, index) => { console.log(`日期${weekDates[index]}的事件:`, result.data); });
这样就能轻松拿到每个日期对应的查询返回值啦~
内容的提问来源于stack exchange,提问作者Mohamed Baher
相关产品推荐
相关产品推荐

