javascript - ReactJs:无法使用地图循环对象数组
问题描述
在尝试遍历从 ReactJs 中的数据库检索到的对象数组时,我总是收到此错误
this.state.getCourse.map is not a function. (In 'this.state.getCourse.map(function (y) {
(Device)
_react.default.createElement(_reactNative.Text, null, y.fullname);
})', 'this.state.getCourse.map' is undefined)
我不知道为什么我总是得到这个错误,就好像我只是使用
<Text>{this.state.getCourse}</Text>
它将以数组对象格式显示保存的对象,如下所示
[{"fullname": "Gbenga", "mail": "t@j.com"},{"fullname": "Femi", "mail": "ht@h.com"}]
但是如果我遍历它,它总是返回上述错误。
这是我到目前为止所做的。
// screens/Attendance.js
import React, { Component } from 'react';
import { Button, View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
class Attendace extends Component {
constructor() {
super();
this.state = {
getCourse: [],
};
}
async componentDidMount(){
try {
await AsyncStorage.getItem('course').then(value =>
//AsyncStorage returns a promise so adding a callback to get the value
this.setState({ getCourse: value })
//Setting the value in Text
);
} catch (e) {
alert(e);
}
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Attendance screen</Text>
{
this.state.getCourse.map((y) => {
<Text>{y.fullname}</Text>
})
} // This will not work
<Text>{this.state.getCourse}</Text>// This will display the array in a json format
</View>
);
}
}
export default Attendace;
解决方案
您正在从 map 函数返回一个对象。您需要添加一个返回或简单地使用短箭头语法,如下所示:
<Text>Attendance screen</Text>
{
this.state.getCourse.map((y) => <Text>{y.fullname</Text>)
} // notice the lack of {}, if you dont like this syntax just add a return before <Text ;
此外,在您修复此 React 后,会抱怨缺少键,因此要么添加索引值(如果数组可以更改,通常不推荐)或使用数据源中的一些唯一值。
推荐阅读
- vb.net - 在驱动器中搜索包含确切单词的文本文件并进行更改
- python - Django Rest Framework 我不能使用有外键的序列化程序保存模型
- bash - Linux bash脚本:将ls与glob一起使用并在变量中获取输出不起作用
- reactjs - 反应选择组合框可访问性。屏幕阅读器未宣布提供的选项
- django - 合并模型并发送到模板
- android - 在没有应用程序上下文或电话权限的情况下生成唯一的设备 ID
- apache-spark - 时间戳转换使值 null
- java - 如何从java jar访问外部文件
- python - 从应用程序机器人向松弛用户发送直接消息,但不在应用程序频道中
- html - 从 HTML 页面检索标签以将它们导入另一个 HTML 文件