React中Fetch获取JSON数组,如何提取对象的QuestId值?
问题原因及解决方法
你的代码报错是因为服务器返回的是包含单个对象的数组,而你直接把它当成单个对象去访问res.QuestId——数组本身没有QuestId属性,所以自然会返回undefined。
修正步骤
- 先从返回的数组中取出第一个元素(也就是包含
QuestId的目标对象),用res[0]获取 - 再访问该对象的
QuestId属性;除非你确实需要存字符串格式,否则不用JSON.stringify包裹(状态存数字更合理) - 另外你代码里
fetch的第二个参数写法有误,写了{却未闭合,若不需要额外请求配置可以直接省略这个参数
修正后的代码
fetch("http://testapi/quest") .then(res => res.json()) .then( res => { // 先取数组第一个元素,再提取QuestId const questId = res[0].QuestId; setQuestId(questId); console.log('Test' + questId); // 用刚获取的questId,而非未定义的qid }, (error) => { alert("Failed" + error); } );
额外优化建议
如果不确定返回的数组是否一定有元素,可以加个判断避免报错:
fetch("http://testapi/quest") .then(res => res.json()) .then( res => { if (res.length > 0) { const questId = res[0].QuestId; setQuestId(questId); console.log('Test' + questId); } else { alert("未获取到任务ID"); } }, (error) => { alert("Failed" + error); } );
内容的提问来源于stack exchange,提问作者Hasan Zubairi
相关产品推荐
相关产品推荐

