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

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

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

{
    "cust_id": 1,
    "given_name": "John",
    "family_name": "Smith",
    "email": "[email protected]",
    "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函数显示的日志消息:“服务器响应是:[对象对象]”

我的单位列表设置:

       <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>}
        />

我在做什么错?

谢谢

reactjs react-native react-native-android
1个回答
0
投票

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

{
    "cust_id": 1,
    "given_name": "John",
    "family_name": "Smith",
    "email": "[email protected]",
    "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))
© www.soinside.com 2019 - 2024. All rights reserved.