【问题标题】:groupby in react native flatlist反应本机平面列表中的groupby
【发布时间】:2021-09-12 21:45:38
【问题描述】:

我正在使用 fetch 和 Flatlist 从 laravel rest api 获取和显示 json 数据。我的 laravel api 输出是这样的

[
{"teacher": "alex","student":"roger","class":"6"}
{"teacher": "alex","student":"simmon","class":"6"}
{"teacher": "alexandra","student":"henry","class":"8"}
....
]

在 react native 中,我使用 fetch api 从 laravel 中获取数据

fetch('http://11.1.1.1:8000/api/get_data/' {
      method: 'get',
    })
      .then((response) => response.json())
      .then((responseJson) => {
         this.setState({ record: responseJson.data})
 })
      .catch((error) => {
        console.error(error);
      });

在 flatlist 中我显示类似的数据

 <FlatList
          data={this.state.record}
          keyExtractor={(item, index) => index + ""}
          ListHeaderComponent={this.tableHeader}
          stickyHeaderIndices={[0]}
          renderItem={ 
            ({item}) => (
              <Text>{item.data.student}</Text>
              <Text>{item.data.class}</Text>


            ) 
          }
        />

我的输出是这样的

sr.no    student    class
1        roger      6
2        simmon     6
3        henry      8

但我想按老师姓名分组,我想要的输出是这样的

alex //teacher name
 sr.no    student    class
    1        roger      6
    2        simmon     6
alexendra //teacher name
 sr.no    student    class
    1        henry      8

如何在flatlist中使用reduce函数来实现那种输出?

【问题讨论】:

    标签: javascript react-native fetch reduce react-native-flatlist


    【解决方案1】:

    您可以构建自己的功能:

    var groupBy = function(xs, key) {
      return xs.reduce(function(rv, x) {
        (rv[x[key]] = rv[x[key]] || []).push(x);
        return rv;
      }, {});
    };
    
    console.log(groupBy(this.state.record, 'teacher'))
    

    或者您可以使用外部库,例如 lodash:

    https://lodash.com/docs/4.17.15#groupBy

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2022-10-01
      • 2022-06-17
      相关资源
      最近更新 更多