reactjs - 如何从一个 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>}
/>
我究竟做错了什么?
谢谢
解决方案
您似乎正在尝试迭代一个普通对象。如果服务器响应是
{
"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))
推荐阅读
- javascript - react-native:axios 得到 500 内部服务器错误
- influxdb - Kapacitor 在添加新字段时创建新点
- google-chrome - 如何开发 Chrome/Firefox 插件(没有扩展!没有 npapi!)
- spring - 在春季将单例注入原型
- asp.net-core - ASP.NET Core DataProtection + Redis + 每台机器多个键
- php - 与正则表达式匹配的目标消息
- json - 通过与指定值完全匹配的任何元素选择数组
- html - 引导页脚调整大小导致页面内容被覆盖
- php - 实体不想刷新 - Symfony 3.4 / Mongodb / Php
- html - 如何在手风琴中锚定链接