【问题标题】:Mapping a nested array of objects in React Native在 React Native 中映射嵌套的对象数组
【发布时间】:2018-04-02 05:59:15
【问题描述】:

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

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: 无法读取未定义的属性“地图”

知道为什么会这样吗?

编辑:

我在等待答案时尝试执行嵌套循环。下面是我的代码sn-p:

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>);
 }
   })
  )
})

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

【问题讨论】:

    标签: javascript arrays reactjs react-native


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

          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)
        }
      )

      【讨论】:

        猜你喜欢
        • 2021-06-23
        • 1970-01-01
        • 1970-01-01
        • 2021-03-29
        • 2022-08-10
        • 2021-02-08
        • 2023-01-23
        • 2020-02-22
        • 2020-09-25
        相关资源
        最近更新 更多