You need to enable JavaScript to run this app. React Native FlatList如何使用reduce实现按教师字段分组展示
优惠活动
大模型
产品
解决方案
定价
更多

React Native FlatList如何使用reduce实现按教师字段分组展示

实现方案

1. 使用reduce对接口返回数据做分组处理

你可以在fetch请求的回调中,先对原始数组按教师姓名分组,再转换为FlatList支持的一维结构(区分教师头部、分组表头、学生行三类数据):

fetch('http://11.1.1.1:8000/api/get_data/', { // 注意原代码这里少了逗号,会触发语法错误
  method: 'get',
})
.then((response) => response.json())
.then((responseJson) => {
  // 按教师姓名分组
  const groupedData = responseJson.data.reduce((acc, cur) => {
    if (!acc[cur.teacher]) {
      acc[cur.teacher] = []
    }
    acc[cur.teacher].push(cur)
    return acc
  }, {})

  // 转换为FlatList可用的一维数组,标记每一项的类型
  const formatList = []
  Object.keys(groupedData).forEach(teacherName => {
    // 插入教师分组头部
    formatList.push({
      type: 'teacher',
      name: teacherName
    })
    // 插入当前分组的表头
    formatList.push({
      type: 'tableHeader'
    })
    // 插入当前教师下的所有学生数据,顺便生成序号
    groupedData[teacherName].forEach((student, idx) => {
      formatList.push({
        type: 'student',
        serialNo: idx + 1,
        data: student
      })
    })
  })

  this.setState({ record: formatList })
})
.catch((error) => {
  console.error(error);
});

2. 调整FlatList渲染逻辑

根据每一项的type字段渲染不同内容,同时修改keyExtractor避免重复:

<FlatList
  data={this.state.record}
  keyExtractor={(item, index) => `${item.type}_${index}`}
  renderItem={({item}) => {
    switch(item.type) {
      // 渲染教师姓名
      case 'teacher':
        return <Text style={{fontWeight: 'bold', fontSize: 16, marginVertical: 8}}>{item.name}</Text>
      // 渲染分组表头
      case 'tableHeader':
        return <View style={{flexDirection: 'row', paddingLeft: 16}}>
          <Text style={{flex: 1}}>sr.no</Text>
          <Text style={{flex: 2}}>student</Text>
          <Text style={{flex: 1}}>class</Text>
        </View>
      // 渲染学生行
      case 'student':
        return <View style={{flexDirection: 'row', paddingLeft: 32}}>
          <Text style={{flex: 1}}>{item.serialNo}</Text>
          <Text style={{flex: 2}}>{item.data.student}</Text>
          <Text style={{flex: 1}}>{item.data.class}</Text>
        </View>
      default:
        return null
    }
  }}
/>

你可以根据自己的设计需求调整各部分的样式缩进、字体大小等属性,即可实现你需要的分组展示效果。

内容的提问来源于stack exchange,提问作者raja ali haider

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 17:33:00