我的json数据是
[
{
"id": 51,
"name": "Boat Neck Blouse",
"image": {
"id": 669,
"date_created": "2018-08-27T10:05:39",
"date_created_gmt": "2018-08-27T10:05:39",
"date_modified": "2018-08-27T10:05:39",
"date_modified_gmt": "2018-08-27T10:05:39",
"src": "https:\/\/dreamdesigners.rkhomeappliances.co.in\/wp-content\/uploads\/2018\/08\/boatneck.jpg",
"title": "boatneck",
"alt": ""
},
"menu_order": 0
}
]
我可以获取Name,id和所有src of image object
,但无法获取。
我尝试过的是
state={
data:[],
}
fetchData = async() => {
const response = await
fetch("mywebsite.com/json");
const posts = await response.json();
this.setState({data:posts});
}
componentDidMount(){
this.fetchData();
}
render() {
return (
<Container>
<ScrollView style={{backgroundColor:'#eeeeee'}}>
<View>
<FlatList contentContainerStyle={styles.list} numColumns={2}
data={this.state.data }
keyExtractor = {(x,i) =>i.toString()}
renderItem = {({item})=>
<TouchableHighlight style={{width:'50%'}} underlayColor="white">
<View style={styles.view} >
<Text>{item.image.src}</Text>
<Text style={styles.text}>{item.name}
</Text>
</View>
</TouchableHighlight>
} />
</View>
</ScrollView>
</Container>
)
}
}
我只是试图显示图像的src,但出现以下错误。
TypeError: undefined is not an object (evaluating '_this3.item.image')
如何从图像对象获取src?我是React Native和React JS的新手。请帮助我获取图像src。
答案 0 :(得分:0)
您必须将this.item.image替换为item.image.src
答案 1 :(得分:0)
[
{
"id": 51,
"name": "Boat Neck Blouse",
"image": {
"id": 669,
"date_created": "2018-08-27T10:05:39",
"date_created_gmt": "2018-08-27T10:05:39",
"date_modified": "2018-08-27T10:05:39",
"date_modified_gmt": "2018-08-27T10:05:39",
"src": "https:\/\/dreamdesigners.rkhomeappliances.co.in\/wp-content\/uploads\/2018\/08\/boatneck.jpg",
"title": "boatneck",
"alt": ""
},
"menu_order": 0
}
]
这是您要访问date_created
的方式(例如)
尝试一下
(假设数据已分配给变量data
)
如您所见,JSON以数组开头,因此您将必须访问数组中的内容。在这种情况下,数组仅包含1个内容。因此,如果您访问data[0]
,则将获得
{
"id": 51,
"name": "Boat Neck Blouse",
"image": {
"id": 669,
"date_created": "2018-08-27T10:05:39",
"date_created_gmt": "2018-08-27T10:05:39",
"date_modified": "2018-08-27T10:05:39",
"date_modified_gmt": "2018-08-27T10:05:39",
"src": "https:\/\/dreamdesigners.rkhomeappliances.co.in\/wp-content\/uploads\/2018\/08\/boatneck.jpg",
"title": "boatneck",
"alt": ""
},
"menu_order": 0
}
然后,如果您想通过date_created
键访问image
,它将为data[0].image.date_created
希望这有助于您了解如何访问JSON数据