我已经为此挣扎了一周了。
我有一个页面,它打印了一个带有值的表格:
name resource_group
Machine-1 Group-1
Machine-2 Group-2
Machine-3 Group-3这些值来自我在Json对象上执行的映射,如下所示:
data = [
{"name": "Machine-1", "resource_group": "Group-1"},
{"name": "Machine-2", "resource_group": "Group-2"},
{"name": "Machine-3", "resource_group": "Group-3"}
]现在我想为这台机器的每台机器添加一个状态值async,这样当页面加载时,它将加载前一个表以及每台机器的状态。我搜索并尝试了foreach循环和for循环,但我找不到一种方法。
输出应如下所示:
name resource_group status
Machine-1 Group-1 on
Machine-2 Group-2 off
Machine-3 Group-3 off为了获得状态值,我有另一个Json对象:
MachineRow = [
{"name": Machine-1, "status": "on"},
{"name": Machine-2, "status": "off"},
{"name": Machine-3, "status": "off"}
]他们有共同的名字,所以我试着使用它。
这就是我到目前为止的工作方式,但方式是错误的,因为每一行的状态都会列出3次:
return (
<div className={classes.root}>
<h1>Azure machines</h1>
<Table className={classes.table} size="small">
<TableHead>
<TableRow>
<TableCell align="left">name</TableCell>
<TableCell align="left">resource_group</TableCell>
<TableCell align="left">location</TableCell>
<TableCell align="left">status</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.map(row => (
<TableRow key={row.name + row.resource_group}>
<TableCell align="left" component="th" scope="row">
<StyledButton size = "small" className={style.size3}>
<Link style={{ color: 'inherit', textDecoration: 'inherit'}} to={`/machines/${row.resource_group + "/" + row.name}`}>{row.name}</Link>
</StyledButton>
</TableCell>
<TableCell align="left">{row.resource_group}</TableCell>
<TableCell align="left">{row.location}</TableCell>
{MAchineRow.map(row => (
<TableCell key= {row.name + row.resource_group}align="left">
<MachineStatusIcon
status_code={row.status_code}
status={row.status}
/>
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
)
}此返回的输出如下所示:
name resource_group status
Machine-1 Group-1 on off off
Machine-2 Group-2 on off off
Machine-3 Group-3 on off off如何才能在不合并对象的情况下逐行打印每台机器的正确状态?它可以在返回中完成吗?谢谢你的帮助
发布于 2020-01-24 22:04:27
不要使用map,使用find。
而不是
{MAchineRow.map(row => (
<TableCell key= {row.name + row.resource_group}align="left">
<MachineStatusIcon
status_code={row.status_code}
status={row.status}
/>
</TableCell>
))}尝试如下所示:
<TableCell key={row.name + row.resource_group) align='left'>
<MachineStatusIcon
status_code={MachineRow.find( ({ name }) => name === row.name).status}
status={MachineRow.find( ({ name }) => name === row.name).status}
/>
</TableCell>https://stackoverflow.com/questions/59897768
复制相似问题