我已在中成功发布数据MongoDB Atlas
,现在我想在我的简单React Native App中显示该数据。数据显示在我的终端中,但是我无法在我的App中显示数据。
这是从数据库获取数据的代码。
display(){
fetch('myUrl', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
title: responseJson,
description: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
这是不在App中显示数据的代码
<TouchableOpacity onPress={()=>this.display()} style={styles.btn}>
<Text style={{textAlign: 'center'}}> Display </Text>
</TouchableOpacity>
<View>
<FlatList
data={this.state.title}
renderItem={({item}) => <Text>{item.title}</Text>}
keyExtractor={({id}, index) => id}
/>
</View>
Flatlist数据属性需要一个数组。
但是您似乎设置了一个对象。
如果您的api返回一个数组,则可以进行以下更改以使其起作用:
state = {
items:[]
}
display() {
fetch('myUrl', { method: 'GET'})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
items: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
如您所见,我使用状态项作为数组,并在收到api响应时更新了其值。
在清单中:
<View>
<FlatList
data={this.state.items}
renderItem={({item}) => <Text key={item._id}>{item.title}</Text>}
keyExtractor={ item => item._id}
/>
</View>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句