如何在反应中从数组中获取动态表头?

问题描述

我试图从我得到的部分数据中循环出一个数组到我的表头中。我使用的是材质-UI 表。

检索到的数据如下所示:

0: {baseclass_id: 1,sortOrder: 1,…}
1:
  baseclass: {baseclass_id: 2,name: "10",…}
  baseclass_id: 2
  periodQuantity: Array(3)
    0: {id: 4,period: "may-21",quantity: 44}
    1: {id: 5,period: "jun-21",quantity: 19}
    2: {id: 6,period: "jul-21",quantity: 31}
  sortOrder: 2
  __proto__: Object
2: {baseclass_id: 3,sortOrder: 3,…}
and so on...

我想循环出该数组,因此表格中的标题将句点值作为标题文本,而下方的单元格则获得了该数量值。

像这样,但不是重复值。 (这张图片只有硬编码值):

enter image description here

这是我来自 tableContent.js 的代码

  export const columnsSortiment =  Object.keys('periodquantity').map((key,id)=>{
    return{
      Header: () => (<div style={{ textAlign: "left" }}><b>{'period'}</b></div>),id: 'id',accessor: 'quantity',Cell: (props) => { return <div style={{ textAlign: "left" }}>{props.cell.value}</div> }
    }
  })

在这里遇到一个错误

错误:在上面的列数组中发现重复列的 id:“id,id,id”

我认为这是因为我有 'periodquantity' 而不是 {periodquantity} 但我不知道如何访问数组。因为当我使用 {periodquantity} 时,我得到了:

'periodquantity' 未定义 no-undef

我也认为它在访问器中有相同名称时出错了。

这是我的monthSortiment.js表:


import React,{ useState } from "react";
import CssBaseline from '@material-ui/core/CssBaseline'
import MaUTable from '@material-ui/core/Table'
import TableContainer from '@material-ui/core/TableContainer'
import TableBody from '@material-ui/core/TableBody'
import TableCell from '@material-ui/core/TableCell'
import TableHead from '@material-ui/core/TableHead'
import TableRow from '@material-ui/core/TableRow'
import TableFooter from '@material-ui/core/TableRow'
import Tooltip from '@material-ui/core/Tooltip'
import { useTable } from 'react-table'
import { makeStyles } from '@material-ui/core/styles';
import _ from "lodash";
import { Col } from "reactstrap";

function Table({ columns,data,update }) {
  const [selectedID,setSelectedID] = useState(null);
  const classes = useStyles();
  // Use the state and functions returned from useTable to build your UI
  const { getTableProps,getTableBodyProps,headerGroups,rows,prepareRow } = useTable({
    columns,update,})

  // Render the UI for your table
  return (
    <TableContainer>
      <Col className="table-size">
        <MaUTable {...getTableProps()} stickyHeader>
          <colgroup>
            <col style={{ width: '5%',textAlign: "right" }} />
            <col style={{ width: '10%',textAlign: "right" }} />
            <col style={{ width: '10%' }} />
            <col style={{ width: '10%' }} />
            <col style={{ width: '10%' }} />
            <col style={{ width: '10%' }} />
            <col style={{ width: '10%' }} />
            <col style={{ width: '10%' }} />
          </colgroup>
          <TableHead>
            {headerGroups.map(headerGroup => (
              <TableRow  {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map(column => (
                  <TableCell className="year-table-cell" style={{ border: 'none' }} {...column.getHeaderProps()}>
                    {column.render('Header')}
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableHead>
          <TableBody {...getTableBodyProps()}>
            {rows.map((row,i) => {
              prepareRow(row)
              return (
                <TableRow {...row.getRowProps()}>
                  {row.cells.map(cell => {
                    return (
                      <TableCell className="year-table-cell" style={{ border: 'none' }} {...cell.getCellProps()}>
                        {cell.render('Cell')}
                      </TableCell>
                    )
                  })}
                </TableRow>
              )
            })}
          </TableBody>
          <TableFooter ></TableFooter>
        </MaUTable>
      </Col>
    </TableContainer>
  )
}
export default Table

这是我的 index.js 文件(console.log() 给出了我在这里粘贴的第一个数据):

import React,{ useState,useEffect,Component } from "react";
import Table from "../../Layout/Shared/TableSelect.js";
import { columns,columnsSortiment,data } from "./tablecontent";
import "some services etc"

const FollowUp = (props: Props) => {
  const [state,setState] = useState([{}]);
  const [dataMonth,setDataMonth] = useState([{}]);
  const tableMonthcolumns = React.useMemo(() => columnsSortiment,[]);

function showMonth() {
  fetchMonth(monthStart,monthEnd);
}
const fetchMonth = (event: any) => {
     monthDateTime.start = monthStart;
     monthDateTime.end = monthEnd;
     monthDateTime.filter = filter;

    followUpService
    .GetDataByMonth(monthDateTime).subscribe(
      (response) => handleMonth(response),(error) => handleHttpRequestError(error.message));
  };
  const handleMonth = (response: any) => {
    setDataMonth(response)
    console.log(response);
  };

 return (
 ... some code

  <Button onClick={() => showMonth(monthStart,monthEnd,filter)}>Ok</Button>
  <Row>
    <Col id="monthTable" style={{ display: (radiovalue == "month" ? "block" : "none") }}>
      <div className="month">
          <FollowUpTable columns={tableMonthcolumns} data={dataMonth} setState={setState} />
      </div>
    </Col>
  </Row>
 ... some code
 );
};
export default FollowUp;

这是我的后端模型代码

public class GetFollowUpModel
{
   public int Baseclass_id { get; set; }
   public int Sortorder { get; set; }
   public BaseclassModel Baseclass{ get; set; }
   public List<PeriodQuantity> PeriodQuantity { get; set; }
}

最后是我的后端服务:

public class FollowUpService : BaseService,IFollowUpService
{
  public List<GetFollowUpModel> GetDataByMonth(FollowUpModel followUpData)
  {
     var sumBaseClassQuantity= new List<GetFollowUpModel>();
     int periodQuantityId = 0;
       foreach (var baseclass in baseclasses)
         {
           var periodQuantityList = new List<PeriodQuantity>();
           string month = "";
           foreach (var m in months)
             {
               var periodQuantity = new PeriodQuantity();
               int? sumQuantity = 0;
               var baseclassInData = data.FindAll(x => x.Baseclass_id == baseclass.Baseclass_id).Where(x => x.Month == m);
               foreach (var item in baseclassInData )
               {
                 if (item.Month == m)
                 {
                   sumQuantity += item.sumQuantity ;
                 }
               }
               periodQuantity.Quantity = sumQuantity;
               periodQuantity.Period = m;
               periodQuantityId += 1;
               periodQuantity.id = periodQuantityId;
               periodQuantityList.Add(periodQuantity);
             }
           }
           sumBaseClassQuantity.Add(new GetFollowUpModel
           {
              Baseclass_id = baseclass.Baseclass_id,Baseclass = baseclass,Sortorder = baseclass.sortorder,PeriodQuantity = periodQuantityList
            });

   return sumBaseClassQuantity;
 }
}

有什么想法吗? (我希望我已将所有正确的变量从瑞典语翻译成英语,以便更好地理解。)

解决方法

您以错误的方式创建列。 以下 react-table 文档 idaccessor 必须是唯一的。

试试这样:

const data = [
  { id: 4,period: 'may-21',quantity: 44 },{ id: 5,period: 'jun-21',quantity: 19 },{ id: 6,period: 'jul-21',quantity: 31 }
]

export const columns = data.map(d => {
  return {
    Header: () => (
      <div style={{ textAlign: 'left' }}>
        <b>{d.period}</b>
      </div>
    ),id: d.id,accessor: d.period
  }
})

然后将数据格式化为如下所示。

const dataForTable = [{ 'may-21': 44 },{ 'jun-21': 19 },{ 'jul-21': 20 }]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...