问题描述
我目前正在尝试提高使用JavasScript,React和Material-UI的技能。我试图使用嵌套的JSON对表进行排序,但我坚持将JSON字段分配给数组。有什么方法可以访问并将JSON分配给数组中的ID?
这是我的JSON的副本:
x
这是我的需要排序的表头数组的源代码:
la(select(head(df),mac,datetime),mac)
[1] "dc:a6:32:21:59:2b"
[[1]]
# A tibble: 6 x 2
mac datetime
<chr> <dttm>
1 dc:a6:32:21:59:2b 2020-07-13 12:50:00
2 dc:a6:32:21:59:2b 2020-07-13 12:55:00
3 dc:a6:32:21:59:2b 2020-07-13 13:00:00
4 dc:a6:32:21:59:2b 2020-07-13 13:05:00
5 dc:a6:32:21:59:2b 2020-07-13 13:10:00
6 dc:a6:32:21:59:2b 2020-07-13 13:15:00
这是我的输出的照片:
分配一个不像状态字段那样嵌套的字段,但是如果它在嵌套中,该怎么办? 我尽了我所能想到的一切,但我想我现在需要你们的帮助。任何帮助,技巧,建议等将不胜感激。谢谢!
EDIT(8/16/20):嗨!这是我的作品的沙盒副本的链接: Table-Sorting-Sandbox
解决方法
您可能要考虑的一种可能的解决方案是先将数据展平-删除嵌套。
您可以使用useEffect
在表呈现之前准备数据。检查下面的代码。
export default function Scheduled() {
const classes = useStyles();
const [order,setOrder] = React.useState("asc");
const [orderBy,setOrderBy] = React.useState("");
// state that will hold the flattened data
const [schedData,setSchedData] = React.useState([]);
React.useEffect(() => {
const { transactions } = SchedData.data;
const schedData = transactions.map((transaction) => {
// make all `details` properties to be accessible
// on the same level as `status`
return { ...transaction,...transaction.details };
});
setSchedData(schedData);
},[]);
const handleRequestSort = (event,property) => {
const isAsc = orderBy === property && order === "asc";
setOrder(isAsc ? "desc" : "asc");
setOrderBy(property);
};
return (
<div className={classes.root}>
<Paper className={classes.paper}>
<TableContainer>
<Table
className={classes.table}
aria-labelledby="tableTitle"
aria-label="enhanced table"
>
<EnhancedTableHead
classes={classes}
order={order}
orderBy={orderBy}
onRequestSort={handleRequestSort}
rowCount={schedData}
/>
<TableBody>
{stableSort(schedData,getComparator(order,orderBy)).map(
(data,index) => {
return (
<TableRow tabIndex={-1} key={index}>
{/* notice here,we don't have to use `data.details` */}
<TableCell>{data.transactionDate}</TableCell>
<TableCell>{data.frequency}</TableCell>
<TableCell>{data.billerName}</TableCell>
<TableCell>{data.sourceAccntNickname}</TableCell>
<TableCell>{data.amount}</TableCell>
<Table>{data.status}</Table>
</TableRow>
);
}
)}
</TableBody>
</Table>
</TableContainer>
</Paper>
</div>
);
}
分支和更新的代码和框: