fetch语句从服务器获取json数据。我想获取要保存在状态中的对象的值。响应只是其中的一个元素 [{"QuestId":1700}]。如何获取QuestId的值。我的代码给出了未定义的错误。
fetch("http://testapi/quest", {
.then(res => res.json())
.then(
res => {
setQuestId(JSON.stringify(res.QuestId))
console.log('Test' + qid);
},
(error) => {
alert("Failed" + error);
}
);
如果
res
的值为 [{"QuestId":1700}]
,则它是一个数组;如果您确定要获得第一个条目,则必须执行 res[0].QuestId
而不是 res.QuestId
。该错误有些指示性 - 数组没有属性 QuestId
。