在React Native

时间:2017-10-21 03:08:27

标签: javascript arrays reactjs react-native

我正在尝试根据其中一个对象显示包含变体的项目列表。请参阅以下代码以获得一些见解:

data: [{
  "transportation": [
    {"id": "1", "name": "bus", "type": "large"},
    {"id": "2", "name": "bicycle", "type": "small"}],
    
  "animal": [
    {"id": "3", "name": "elephant", "type": "large"},
    {"id": "4", "name": "mouse", "type": "small"}]
 }]

对于上面的示例,我想显示一些简单的东西,如“大”文本,如果类型是“大”和“小”文本,如果类型“小”。我想到的第一件事是做一个嵌套的地图(数据的外部地图,交通/动物的内部地图)。我首先测试内部地图而没有外部地图,如下图所示:

data.animal.map((info) => {
  switch (info.type){
    case "large":
      return(
        <View>
        <Text>Large</Text>
        </View>);

    case "small":
      return(
       <View>
       <Text>Small</Text>
       </View>);
         
    default:
      return(
        <View>
        <Text>Whatever</Text>
        </View>);
  }
})

我得到了

  

TypeError:无法读取未定义

的属性“map”

知道为什么会这样吗?

修改

我在等待答案时曾试图做一个嵌套循环。以下是我的代码段:

data.map((category, key) => {
  return(
    Object.keys(category).map((info) => {
    switch (info.type){
    case "large":
    return(
    <View>
    <Text>Large</Text>
    </View>);
    
    case "small":
    return(
    <View>
    <Text>Small</Text>
    </View>);
    
    default:
    return(
    <View>
    <Text>Whatever</Text>
    </View>);
 }
   })
  )
})

它运行没有错误,但它没有给我预期的结果。所有输出都切换到默认值,即“Whatever”。

2 个答案:

答案 0 :(得分:1)

您正在访问数据阵列的第一个对象。所以你的代码应该是

data[0].animal.map((info) => {
....

答案 1 :(得分:0)

&#13;
&#13;
    data = [{
  "transportation": [
    {"id": "1", "name": "bus", "type": "large"},
    {"id": "2", "name": "bicycle", "type": "small"}],
    
  "animal": [
    {"id": "3", "name": "elephant", "type": "large"},
    {"id": "4", "name": "mouse", "type": "small"}]
 }]


data[0].animal.map((info) => {
   return console.log(info)
  }
)
&#13;
&#13;
&#13;