You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native嵌套JSON数据访问异常:仅显示最后一项求助

问题解决:嵌套JSON仅显示最后一项内容

问题根源

你的JSON数据中contents数组的结构有误——你把多个title字段放在了同一个对象里。在JavaScript对象中,重复的键会被最后一次赋值覆盖,所以每个contents数组里实际上只有最后一个title生效,前面的都被丢弃了。

修正后的JSON数据

把每个菜品拆成独立的对象,每个对象只保留一个title字段:

let tableData = [
  { 
    "id":"1",
    "title":"Joe's Gelato", 
    'tagline':"Desert, Ice cream, £££", 
    'eta':"10-30",
    'imgUri':require('./assets/nasi-briyani-mutton.jpg'),
    'items':[ 
      {"title":"Gelato", 
        "contents":[
          {"title":"Vanilla"},
          {"title":"Chocolate"},
          {"title":"Mint"}  
        ]},
      {"title":"Coffee", 
        "contents":[
          {"title":"Flat white"},
          {"title":"Latte"},
          {"title":"Caffe Americano"}  
        ]}  
    ]
  },
  { 
    "id":"2",
    "title":"Joe's Dinner", 
    'tagline':"Pizza, burgers, £££", 
    'eta':"50+",
    'imgUri':require('./assets/pizza-restaurant.jpg'),
    'items':[
      {"title":"Pizza", 
        "contents":[
          {"title":"Roco Pizza"},
          {"title":"Veggi"},
          {"title":"Chicken Supreme"}  
        ]},
      {"title":"Burger", 
        "contents":[
          {"title":"Cubby Burger"},
          {"title":"Rock Burger"},
          {"title":"Chicken Lover"}  
        ]}  
    ]
  },
];

React代码无需修改

你的React遍历逻辑是正确的,修正JSON结构后,menuSection.contents.map会遍历每个独立的菜品对象,就能完整显示所有菜品了:

<ScrollView>
  <TableView>         
    <Text>---Menu---</Text>
    {tableData[0].items.map ((menuSection,i) => (
      <Section header={menuSection.title}>
        {menuSection.contents.map((dishes,j) => ( 
          <Cell title={dishes.title}/> 
        ))}
      </Section>
    ))}
  </TableView>
</ScrollView>

内容的提问来源于stack exchange,提问作者Ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:40:26