首页 > 解决方案 > 如何在 React Native ListView 中过滤和呈现重复的嵌套 JSON 数据?

问题描述

我是 JSON 和过滤的新手。下面的data.json文件和FolderScreen.jsreact native ListView. With react-navigationprops 被传递下来以渲染ListView.

这可以完美地用于Chapter 1和渲染它Subchapter AB并且CListView......</p>

1级>第1章

A 分章

B 分章

C分章

…但是一旦Subchapter A被传递到FolderScreen.js中,它的所有Sub-Subchapters A1,A2A3没有按预期在ListView下面的代码片段中呈现…</p>

第 2 级 > A 分章

分章 A1

分章 A2

分章 A3

…我在 JSON 过滤器中遗漏了什么吗?

还是只是做错了?


数据.json

{
   "id":"chapter-1",
   "name":"Chapter 1",
   "type":"folder",
   "content":[
  {
     "id":"sub-chapter-a",
     "name":"Subchapter A",
     "type":"folder",
     "content":[
        {
           "id":"sub-sub-chapter-a1",
           "name":"Sub-Subchapter A1",
           "type":"file"
        },
        {
           "id":"sub-sub-chapter-a2",
           "name":"Sub-Subchapter A2",
           "type":"file"
        },
        {
           "id":"sub-sub-chapter-a3",
           "name":"Sub-Subchapter A3",
           "type":"file"
        }
     ]
  },
  {
     "id":"sub-chapter-b",
     "name":"Subchapter B",
     "type":"file"
  },
  {
     "id":"sub-chapter-c",
     "name":"Subchapter C",
     "type":"file"
  }
   ]
}


文件夹屏幕.js

renderRow = () => {

const entry = this.props.navigation.getParam('chapterID', '');

const listEntry = jsonData.map(all =>
    all.content.filter(parent => parent.id === entry).map(item =>
        item.content.map(i => {
            return (
                <ListEntry
                    id={i.id}
                    name={i.name}
                    type={i.type}
                    navigation={this.props.navigation}
                    key={i.id}
                />
            );
        })
    )
);

return listEntry;
};


非常感谢您的帮助!

标签: javascriptarraysjsonreact-nativefilter

解决方案


这是个简单的。您的代码希望始终有一个content属性是一个数组(或者是一个具有.map()方法的对象,无论如何)。

在最内层,没有"content": []财产。

content在您尝试使用它之前添加一个,或者只是为该属性添加一个签到。

我最喜欢的技术是使用(item.content || []).map(..., 如果属性为 null 或未定义,则使用空数组。


推荐阅读