将 fetch 的响应响应为 json

问题描述 投票:0回答:1

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);
        }
      );
javascript reactjs fetch setstate
1个回答
0
投票

如果

res
的值为
[{"QuestId":1700}]
,则它是一个数组;如果您确定要获得第一个条目,则必须执行
res[0].QuestId
而不是
res.QuestId
。该错误有些指示性 - 数组没有属性
QuestId

© www.soinside.com 2019 - 2024. All rights reserved.