访问&理解反应原生的SectionList

时间:2018-03-23 09:40:33

标签: ios react-native reactive-programming react-native-ios

我是反应原生的新手,我来自iOS背景。 有人可以跟我说关于关于iOS的Sectionlist。我已经通过了几个教程官方和博客但无法理解。 我有一个sampl json:

[{"key":"New","data":[{"name":"Foo1"},{"name":"Foo2"}]},{"key":"Old","data":[{"name":"Foo3"},{"name":"Foo4"}]}]

通过“https://stackoverflow.com/a/46601402”的一些理解,我正在尝试访问项目名称,我得到了结果,名称正在显示。但是当我把儿子换成:

[{"key":"New","gender":"male","name":{"title":"mr","first":"janique","last":"costa"},"registered":"2014-09-22 22:38:28","phone":"(48) 4518-1459","cell":"(22) 3632-3660"},{"key":"New11111","gender":"male11111","name":{"title":"mr11111","first":"janique11111","last":"costa11111"},"registered":"2014-09-22 22:38:2811111","phone":"(48) 4518-145911111","cell":"(22) 3632-366011111"}]

并尝试访问性别,我收到错误:“TypeError:undefined不是对象(评估'section.data.length')”

_renderItem = ({ item, section }) => (<Text>{section.key}</Text>)

    _renderSectionHeader = ({ section }) => {
      return (
        <View style={styles.sectionHeader}>
          <Text style={styles.header}>{section.key}</Text>
        </View>
      )
    }

render() {
    return (


      <View style={styles.container}>
        <SectionList
            sections={data}
            renderItem={this._renderItem}
            renderSectionHeader={this._renderSectionHeader}
        />
      </View>


    );
  }

1 个答案:

答案 0 :(得分:2)

根据SectionList,传递给sections属性的对象必须是具有data属性的对象数组,该属性也必须是数组。您所做的更改不包含data部分,因此有效的JSON可能是

[
  {
    key: "New1", 
    data: [{"gender":"male","name":{"title":"mr","first":"janique","last":"costa"},"registered":"2014-09-22 22:38:28","phone":"(48) 4518-1459","cell":"(22) 3632-3660"}]
  },
  {
    key: "New2", 
    data: [{"gender":"male11111","name":{"title":"mr11111","first":"janique11111","last":"costa11111"},"registered":"2014-09-22 22:38:2811111","phone":"(48) 4518-145911111","cell":"(22) 3632-366011111"}]
  },
  // When data is empty, send empty array as shown below not null or empty object
  {
    key: 'New3',
    data: []
  }
];

希望这有帮助。