首页 > 解决方案 > 如何迭代数据组并以列表形式返回

问题描述

我有这样的数据

0: {rowid: "4b531532a5a9", groups: "Group1", descriptions: "Item1"......}
1: {rowid: "e55315ccabb5", groups: "Group2", descriptions: "Item2"......}
2: {rowid: "f27135283089", groups: "Group1", descriptions: "Item3"......}

我需要像这样展示它https://codesandbox.io/s/material-demo-fwi6f?file=/demo.js

所以首先,当我从 API 获取数据时,首先我在下面做(groupBy 是一个 lodash 方法,它通过数据和按属性分组)

let list = groupBy(response.data, "groups");
      this.setState({
        Groups: Object.keys(list),
        BackOffice: response.data,
      });

这样我就可以将所有组名和数据保存到状态中。然后我到目前为止有下面的代码来创建一个完整的列表,但我不确定为什么它不起作用..

GetBackOffice = () => {
    return (
      <Grid item xs={12}>
        <List dense style={{ padding: 0, margin: 0 }}>
          {this.GetList()}
        </List>
      </Grid>
    );
  };

  GetList = () => {
    let list = "";
    this.state.Groups &&
      this.state.Groups.map((EachGroup) => {
        let CurrentData = this.state.BackOffice.filter(
          (row) => row.groups === EachGroup
        );
        list += CurrentData.map((row) => (
          <ListItem>
            <ListItemText primary="1" />
            <ListItemSecondaryAction>
              <IconButton edge="end" aria-label={row.descriptions}>
                <DownloadIcon />
              </IconButton>
            </ListItemSecondaryAction>
          </ListItem>
        ));
      });

    return list;
  };

标签: javascriptreactjslistmaterial-ui

解决方案


https://codesandbox.io/s/material-demo-w5dl3
在映射的同时 使用flatMap来展平数组

GetList = () =>
  this.state.Groups &&
  this.state.Groups.flatMap(EachGroup => {
    let CurrentData = this.state.BackOffice.filter(
      row => row.groups === EachGroup
    );
    return CurrentData.map(row => (
      <ListItem>
        <ListItemText primary="1" />
        <ListItemSecondaryAction>
          <IconButton edge="end" aria-label={row.descriptions}>
            <DownloadIcon />
          </IconButton>
        </ListItemSecondaryAction>
      </ListItem>
    ));
  });

https://codesandbox.io/s/material-demo-x7edo
我建议直接将 groupBy 返回的对象与Object.values()(或 Object.entries())一起使用,而不是每次都按键过滤:

  GetData = () => {
    const Groups = groupBy(response.data, "groups");
    this.setState({
      Groups
    });
  };

  GetList = () =>
    this.state.Groups &&
    Object.values(this.state.Groups).map(CurrentData => {
      return CurrentData.map(row => (
        <ListItem key={row.rowid}>
          <ListItemText primary="1" />
          <ListItemSecondaryAction>
            <IconButton edge="end" aria-label={row.descriptions}>
              <DownloadIcon />
            </IconButton>
          </ListItemSecondaryAction>
        </ListItem>
      ));
    });

推荐阅读