使用具有两个完全不同的数据数组的 React Native FlatList

Using a React Native FlatList with two completely different arrays of data

我有两个数组,一个用于产品,一个用于主管。显然,两者都有非常不同的数据类型。我想创建一个可滚动列表,该列表将使用单个滚动列表显示所有主管随后显示的所有产品。 React Native 的 FlatList 可以做到这一点吗?如果是,或者如果不是,我该怎么做?

我目前可以按如下方式呈现单个数据数组:

<FlatList
    data={this.state.products}
    renderItem={this.renderItem}
/>

但是,如何将主管数据附加到此列表的末尾?显然,因为两个数组之间的数据完全不同,我不能简单地合并数组和/或相同的 renderItem 函数。

如何在同一个滚动列表中依次显示两种完全不同类型的数据?

您可以将数据合并在一起,并使用带有单个 renderItem 道具的单个 FlatList。在没有数据样本的情况下,这是一个小猜谜游戏,但下面是一个示例。

例子

假设您的数据结构如下。

const Products = [
  {
    id: 1,
    name: 'Product 1'
  },
  {
    id: 2,
    name: 'Product 2'
  },
  {
    id: 3,
    name: 'Product 3'
  },
  {
    id: 4,
    name: 'Product 4'
  },
];

const Supervisors = [
  {
    belongsToPruduct: 1,
    name: 'SuperVisor 1' 
  },
  {
    belongsToPruduct: 3,
    name: 'SuperVisor 2' 
  },
  {
    belongsToPruduct: 2,
    name: 'SuperVisor 3' 
  },
  {
    belongsToPruduct: 4,
    name: 'SuperVisor 4' 
  }
];

并且假设您在 FlatList 中渲染 Products。您可以在 renderItem 函数

中执行如下操作
renderItem = ({ item }) => {
  const superviors = Supervisors.filter((supervisor) => supervisor.belongsToPruduct === item.id)
  return (
    <View style={styles.productContainer}>
      <Text style={styles.productName}>{item.name}</Text>
        <View style={styles.supervisorsContainer}>
          {
            superviors.map((supervisor) => <Text style={styles.supervisorName}>{supervisor.name}</Text>)
          }
        </View>
    </View>
  )
}

更新

参考您的评论,我认为您可以使用 SectionList 而不是 FlatList

<SectionList 
   renderSectionHeader={({ section: { title } }) => <Text style={{ fontWeight: 'bold' }}>{title}</Text>} 
   sections={[ 
     { title: 'Products', data: Products, renderItem: ({ item, index, section: { title, data } }) => <Text>{item.name}</Text> }, 
     { title: 'Supervisors', data: Supervisors, renderItem: ({ item, index, section: { title, data } }) => <Text>{item.name}</Text>}, 
    ]} 
   keyExtractor={(item, index) => item.name + index} 
 />

我通过创建包含 FlatList 个组件的第三个数组来做到这一点。然后只用新的 FlatList component

渲染第三个数组