首页 > 解决方案 > 如何从一个 JSON 对象中提取数据并将其呈现到平面列表中

问题描述

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

{
    "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”
        }
      }
    ]
}

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

custDetails: [] 状态

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);
         });
   }

但是当我尝试在平面列表中呈现客户详细信息时,什么都没有出现,也没有出现错误。getCust 函数显示的日志消息:“服务器响应为:[object Object]”

我的平面列表设置:

       <FlatList
           data={this.state.custDetails}
           keyExtractor={({ cust_id}) => cust_id}
           renderItem={({ cust}) => <View style={styles.list}>
              <Text style={styles.ListText}>{cust.cust_id }</Text>
              <Text style={styles.ListText}>{cust.given_name}</Text>
              <Text style={styles.ListText}>{cust.family_name}</Text>
              <Text style={styles.ListText}>{cust.email}</Text>
           </View>}
        />

我究竟做错了什么?

谢谢

标签: reactjsreact-nativereact-native-android

解决方案


您似乎正在尝试迭代一个普通对象。如果服务器响应是

{
    "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))

推荐阅读