如何从一个JSON对象提取数据并将其呈现到一个列表中

时间:2020-03-18 11:15:56

标签: reactjs react-native react-native-android

我正在创建一个,从API服务器请求客户及其详细信息。这是发送回的响应:

v-b-modal.modal-{{index}}

这是我的get GET函数,它获取响应并将其存储在:

custDetails:[]状态

{
    "cust_id": 1,
    "given_name": "John",
    "family_name": "Smith",
    "email": "smith99@hotmail.com",
    "recent_purchases": [
        {
            "item_id": 1,
            "price": 20,
            "item_descr": "Small apple”
        },
        {
            "item_id ": 2,
            " price ": 15,
            "item_descr": "Sponge Cake”
        }
      }
    ]
}

但是,当我尝试在清单中呈现客户详细信息时,什么也没有出现,也没有错误出现。 从getCust函数显示的日志消息: “服务器响应是:[对象对象]”

我的单位列表设置:

getCustDetails () {
      return fetch(‘API URL HERE’,  
         {
            method: 'GET',
            headers: {
               'Content-Type': 'application/json',
            },
         })
         .then((res) => res.json())
         .then((resJson) => {
            this.setState({
               custDetails: resJson,
            });
            console.log("The server response is :" + this.state.userDetail)
         })
         .catch((error) => {
            console.log(error);
         });
   }

我在做什么错了?

谢谢

1 个答案:

答案 0 :(得分:0)

似乎您正在尝试遍历一个普通对象。如果服务器响应为

{
    "cust_id": 1,
    "given_name": "John",
    "family_name": "Smith",
    "email": "smith99@hotmail.com",
    "recent_purchases": [
        {
            "item_id": 1,
            "price": 20,
            "item_descr": "Small apple”
        },
        {
            "item_id ": 2,
            " price ": 15,
            "item_descr": "Sponge Cake”
        }
      }
    ]
}

您的setState应该为

this.setState({
    custDetails: [resJson],
});

您必须使用[object Object]来控制台JSON.stringify

console.log("The server response is :" + JSON.stringify(this.state.userDetail))