Reactjs 如何从一个JSON对象提取数据并将其呈现到平面列表中
我正在创建一个从API服务器请求客户及其详细信息的应用程序。这是返回的响应:Reactjs 如何从一个JSON对象提取数据并将其呈现到平面列表中,reactjs,react-native,react-native-android,Reactjs,React Native,React Native Android,我正在创建一个从API服务器请求客户及其详细信息的应用程序。这是返回的响应: { "cust_id": 1, "given_name": "John", "family_name": "Smith", "email": "smith99@hotmail.com", "recent_purchases": [ { "item_id": 1, "price": 20, "i
{
"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函数,它获取响应并将其存储在:
客户详细信息:[]状态
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>}
/>
cust\u id}
renderItem={({cust})=>
{cust.cust_id}
{cust.given_name}
{cust.family_name}
{cust.email}
}
/>
我做错了什么
谢谢您似乎正在尝试对普通对象进行迭代。如果服务器响应为
{
"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”
}
}
]
}
你的状态应该是
this.setState({
custDetails: [resJson],
});
由于必须使用JSON.stringify
,所以控制台会记录[object object]
console.log("The server response is :" + JSON.stringify(this.state.userDetail))
您是否检查了当前的
状态
?