react-native - 如何在本机反应中显示获取的数据
问题描述
我成功地在中发布了数据MongoDB Atlas
,现在我想在我的简单反应原生应用程序中显示该数据。数据显示在我的终端中,但我无法在我的应用程序中显示数据。
这是从数据库获取数据的代码。
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);
});
}
如您所见,我将 state 中的项目用作数组,并在收到 api 的响应时更新了它的值。
在平面列表中:
<View>
<FlatList
data={this.state.items}
renderItem={({item}) => <Text key={item._id}>{item.title}</Text>}
keyExtractor={ item => item._id}
/>
</View>
推荐阅读
- c# - 格式不保留在 closedXML 中
- sql - 需要帮助从 sql server 中的其他表在主表中插入新行
- mysql - 优化 Laravel Eloquent?
- php - 加载我构建的 PHP 模块失败,没有错误
- c# - 无法在 Xamarin 中加载 nlog.config
- maven - 使用 spotify maven 插件在 Windows 10 上使用 Docker 创建 Springboot 映像
- php - MYSQL 将 group by 记录限制为 3
- haskell - 打印 haskell-servant API 定义中的所有路由?
- jquery - 如何在从 Pandoc 生成的 html 文件中创建脚注工具提示
- react-native - 在本机反应中未返回平面列表内的组件