我想问一下,是否有更简单的方法来显示数据。这是我的虚拟数据:
const data = [
{
business: false,
utilization: {
ActiveParticipantsPercent: 55.55,
SeparatedVestedParticipants: 0,
ParticipantsWithBenefitAccount: 8,
AverageActiveParticipants: 5,
TotalContributions: 23890
},
year: 2018
},
{
business: true,
utilization: {
ActiveParticipantsPercent: 82.4,
SeparatedVestedParticipants: 1.94,
ParticipantsWithBenefitAccount: 95393,
AverageActiveParticipants: 0.01,
TotalContributions: 257094.79
},
year: 2018
}
];我想在两列中显示数据--一个是2018年的假商业价值,另一个是2018年的真实商业价值。对于它们中的每一个,我都希望显示利用率字段的数据。
我准备了沙箱来查看我是如何做到的,但我认为可能有更简单的方法来做到这一点,并节省资源:https://codesandbox.io/s/immutable-worker-ixf6r?file=/src/App.js
有什么建议吗?还是应该这样保留?
发布于 2020-10-01 00:16:01
您可以在utilization对象(行)和行内部进行迭代,在数据数组(单元格)之间迭代,而不是硬编码每个TableRow,然后在其中迭代。
示例:
// basically the number of rows based on utilization properties plus the header (+1)
let rowCount = Object.keys(data[0].utilization).length + 1;
<TableContainer component={Paper}>
<Table size="small" aria-label="a dense table">
<TableBody>
{[...Array(rowCount)].map((_, i) => {
let current_utilization_key =
i === 0 ? "Field" : Object.keys(data[0].utilization)[i - 1];
return (
<TableRow key={i}>
<TableCell>{current_utilization_key}</TableCell>
{data.map((el, j) => {
let cell_content = "";
// just some condition statements to determine if cell is to be a header or if business evaluates to true
if (i === 0) {
if (el.business === true) {
cell_content = "Business for " + el.year;
} else {
cell_content = el.year;
}
} else {
cell_content = el.utilization[current_utilization_key];
}
return <TableCell key={j}>{cell_content}</TableCell>;
})}
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
https://stackoverflow.com/questions/64133621
复制相似问题