首页 > 解决方案 > 部分列表不显示

问题描述

遵循 React-Native 教程,我无法获得要显示的数据。

当我执行 console.log 时,我的数据如下所示:

Array [
  Object {
    "data": Object {
      "address": "8753 2nd Street",
      "id": "5507",
      "inspection_date": "2019-03-27",
      "inspection_time": "07:00:00",
      "inspection_time_display": "07.00 AM",
      "inspector": "Frank",
    },
    "key": "5507",
    "title": "8753 2nd Street",
  },
  Object {
    "data": Object {
      "address": "11445 Paramount ave ",
      "id": "5505",
      "inspection_date": "2019-03-23",
      "inspection_time": "10:30:00",
      "inspection_time_display": "10.30 AM",
      "inspector": "Fabian Hernandez",
    },
    "key": "5505",
    "title": "11445 Paramount ave ",
  },
]

如大多数教程中所示,我有“数据”和“标题”部分。

我的组件是这样的:

 <Container>
    <Header />
    <Content>
    <SectionList
      renderItem={({item, index, section}) => <Text key={index}>{item}</Text>}
      renderSectionHeader={({section: {title}}) => (
        <Text style={{fontWeight: 'bold'}}>{title}</Text>
      )}
      sections={this.state.dataSource}
      keyExtractor={(item, index) => item + index}
    />
    </Content>
  </Container>

这就是我认为正在发生的事情,但我显然错了,因为有些事情没有加起来。循环遍历“部分”

renderItem={({item, index, section}) => <Text key={index}>{item}</Text>}

我期待上面的这个能得到“数据”。

获取标题:

renderSectionHeader={({section: {title}}) => (
            <Text style={{fontWeight: 'bold'}}>{title}</Text>
          )}

我期待上面的这个得到“标题”。我错过了什么或做错了什么?

标签: react-native

解决方案


我相信每个部分对象中的数据键本身都需要是一个数组。例子:

const mySectionedData = [
  {
    title: 'section 1',
    data: [ 
      {address: '123 street', name: 'me'}, 
      {address: '456 street', name: 'you}
    ]
  },
  {
    title: 'section 2',
    data: [ 
      {address: '789 street', name: 'us'} 
    ]
  }
]

然后,这使您可以{title, data}从每个部分访问,这允许部分列表然后从标题呈现您的部分标题,并从数据数组中呈现项目列表。

希望有帮助!


推荐阅读