React中调用GetObjectives函数时result[0]返回undefined问题排查
问题根源与修复方案
核心问题:异步遍历未正确等待
你的GetObjectives函数存在异步遍历未等待完成就返回结果的问题:
querySnapshot.forEach(async (nodeDoc) => { ... })中,forEach不会等待异步回调执行完毕,遍历结束后直接返回空的objectivesArray。- 浏览器控制台的
console.log是引用式输出,后续异步操作完成后数组被填充,控制台会更新显示内容,但执行console.log(result[0])时,数组还没有元素,所以返回undefined。
修复步骤
1. 修正异步遍历逻辑
把forEach替换成map,将每个异步操作转为Promise,再用Promise.all等待所有Promise完成后再返回结果:
export async function GetObjectives(docId) { try { const querySnapshot = await getDocs(collection(db, "users", "userIdNotAvailableForTheMoment", "documents", docId, "nodes")); // 用map生成Promise数组,再用Promise.all等待所有异步操作完成 const objectivesArray = await Promise.all( querySnapshot.docs.map(async (nodeDoc) => { const nodeId = nodeDoc.id; const objectivesQuerySnapshot = await getDocs(collection(db, "users", "userIdNotAvailableForTheMoment", "documents", docId, "nodes", nodeId, "objectives")); return objectivesQuerySnapshot.docs.map((objectiveDoc) => ({ ...objectiveDoc.data(), id: objectiveDoc.id })); }) ); return objectivesArray; } catch (error) { console.error('Error during the recuperation of objectives : ', error); return null; } }
2. 修正调用代码的参数问题
你的调用代码传了两个参数给GetObjectives,但函数定义只接收docId一个参数,这会导致第二个参数被忽略,需要根据实际需求调整:
// 假设只需要docId参数 GetObjectives(sortDocuments[parseInt(selectedDocument)].id) .then((result) => { console.log(result); console.log(result[0]); // 现在能正确获取第一个元素 });
验证说明
修复后,Promise.all会等待所有节点的目标数据查询完成,确保返回的objectivesArray是填充好的二维数组,此时调用result[0]就能正确获取到第一个子数组。
内容的提问来源于stack exchange,提问作者Thibault Falezan
相关产品推荐
相关产品推荐

