首页 > 解决方案 > 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;

标签: javascriptreactjsreact-native

解决方案


您正在从 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 后,会抱怨缺少键,因此要么添加索引值(如果数组可以更改,通常不推荐)或使用数据源中的一些唯一值。


推荐阅读