首页 > 解决方案 > 如何在本机反应中显示获取的数据

问题描述

我成功地在中发布了数据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> 

标签: react-native

解决方案


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> 

示例代码框


推荐阅读