You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Inverted FlatList分组同日期API响应数组项

按日期分组API数据适配Inverted FlatList

核心思路

先用reduce按日期字段把同日期的项归为一组,再将分组后的对象转换为FlatList可直接使用的数组结构,最后根据Inverted的需求调整排序方向。

代码实现步骤

1. 定义API响应示例与预期结构

// API返回的原始数据
const apiResponse = [
  { id: 1, date: '2024-05-20', content: '消息A' },
  { id: 2, date: '2024-05-20', content: '消息B' },
  { id: 3, date: '2024-05-19', content: '消息C' },
  { id: 4, date: '2024-05-21', content: '消息D' },
];

// 目标分组结构
const targetGroupedData = [
  {
    date: '2024-05-21',
    items: [{ id: 4, date: '2024-05-21', content: '消息D' }]
  },
  {
    date: '2024-05-20',
    items: [
      { id: 1, date: '2024-05-20', content: '消息A' },
      { id: 2, date: '2024-05-20', content: '消息B' }
    ]
  },
  {
    date: '2024-05-19',
    items: [{ id: 3, date: '2024-05-19', content: '消息C' }]
  }
];

2. 分组并转换数据

// 第一步:按日期分组
const groupedObj = apiResponse.reduce((acc, item) => {
  // 以日期为键初始化数组
  if (!acc[item.date]) {
    acc[item.date] = [];
  }
  acc[item.date].push(item);
  return acc;
}, {});

// 第二步:转换为数组并按日期降序排序(适配Inverted FlatList,最新日期在顶部)
const groupedData = Object.entries(groupedObj)
  .map(([date, items]) => ({ date, items }))
  .sort((a, b) => new Date(b.date) - new Date(a.date));

3. 适配Inverted FlatList使用

import { FlatList, View, Text, StyleSheet } from 'react-native';

// 组件内渲染
<FlatList
  inverted
  data={groupedData}
  keyExtractor={(item) => item.date}
  renderItem={({ item }) => (
    <View style={styles.groupContainer}>
      {/* 日期标题 */}
      <Text style={styles.dateText}>{item.date}</Text>
      {/* 渲染同日期下的所有子项 */}
      {item.items.map((subItem) => (
        <Text key={subItem.id} style={styles.itemText}>
          {subItem.content}
        </Text>
      ))}
    </View>
  )}
/>

// 样式示例
const styles = StyleSheet.create({
  groupContainer: { marginVertical: 8 },
  dateText: { fontSize: 12, color: '#999', textAlign: 'center', marginBottom: 4 },
  itemText: { fontSize: 16, padding: 12, backgroundColor: '#f5f5f5', borderRadius: 8, marginHorizontal: 16, marginVertical: 2 }
});

关键注意事项

  • 日期格式统一:如果API返回的日期格式不标准(如2024/05/20、May 20, 2024),需先转换为统一格式(如YYYY-MM-DD)作为分组键,避免分组错误。
  • 子项排序:若同日期内的项需要按时间先后排序,可在reduce分组时对每个子数组额外排序:
    acc[item.date].sort((a, b) => {
      // 假设item包含time字段,如'14:30:00'
      return a.time.localeCompare(b.time);
    });
    
  • Inverted排序调整:如果你的Inverted FlatList需要最新的日期组在底部,只需将排序逻辑改为升序:
    .sort((a, b) => new Date(a.date) - new Date(b.date));
    

内容的提问来源于stack exchange,提问作者Vishali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 17:50:41