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
相关产品推荐
相关产品推荐

