[英]how do I fix my code in order to display one table?
我正在尝试渲染我的动态 JSON,但是当它应该在同一个表中渲染时,我得到了每个结果的表。这是怎么回事? 我的虚拟数组是来自我的后端 api 的 model
const arr = [
{
"Demo": [
{
"_id": "T08210",
"name": "tilehaha",
"tags": [
"Demo"
],
"queries": [],
"urls": [],
"max_leght": [],
"count_items": []
},
],
}
];
export default function Demo() {
return (
<div>
{arr.map(obj =>
Object.entries(obj).map(([key, value]) => (
<table class="table">
<thead>
<tr key={key}>
<th scope="col">{key}</th>
</tr>
</thead>
<tbody>
<tr>
<td>{value.activityType}</td>
<td>{value.durationInSeconds}</td>
</tr>
</tbody>
</table>
)))}
</div>
);
}
尝试这个。
<table class="table">
<thead>
<tr>
{arr.map(obj => Object.entries(obj).map(([key, value]) => (
<th scope="col">{key}</th>
)))}
</tr>
</thead>
<tbody>
{arr.map(obj => Object.entries(obj).map(([key, value]) => (
<tr>
<td>{value.activityType}</td>
<td>{value.durationInSeconds}</td>
</tr>
)))}
</tbody>
</table>
根据您的评论,这似乎是您想要的:
注意未来的观点 - 现在不适用于更改后的问题:
const modArray = Object.keys(arr[0]).map(i => {
return {id: i, ...arr[0][i]}
});
const rowKeys = Object.keys(modArray[0]).filter(i => i !== "id")
export default function Demo() {
return (
<div>
<table class="table">
<thead>
<tr>
{modArray.map(i => <th key={i.id}>{i.id}</th>)}
</tr>
</thead>
<tbody>
<tr>
{modArray.map(item => <td key={item.id}>{item.activityType}</td>)}
</tr>
<tr>
{modArray.map(item => <td key={item.id}>{item.durationInSeconds}</td>)}
</tr>
{/* Or, do it dynamically */}
{rowKeys.map(rowKey => <tr key={rowKey}>
{modArray.map(item => <td key={item.id}>{item[rowKey]}</td>)}
</tr>)}
</tbody>
</table>
</div>
);
}
请注意,在该代码示例的顶部,我将您的输入转换为更可用的格式。 例如,你开始的arr
是一个只有 1 个 object 的数组,它有多个键,这似乎是你想要迭代的数组。
希望这至少接近您正在寻找的内容。
更新 2,根据您更改的问题:
export default function Demo() {
return (
<div>
<table className="table">
<thead>
<tr>
{arr[0]["Demo"].map(i => <th key={i._id}>{i._id}</th>)}
</tr>
</thead>
<tbody>
<tr>
{arr[0]["Demo"].map(item => <td key={item._id}>{item.name}</td>)}
</tr>
</tbody>
</table>
</div>
);
}
问题在这里:
{arr.map(obj =>
Object.entries(obj).map(([key, value]) => (
<table class="table">
在这里,您已将整个表格放入循环中,而不是放入单个表格行。 因此,在每次迭代中,它都会生成一个新表。 要解决此问题,请尝试以下操作:
尝试这个:
<table class="table">
<thead>
<tr>
<th scope="col">Heading 1</th>
<th scope="col">Heading 2</th>
</tr>
</thead>
<tbody>
{
arr.map(obj =>
Object.entries(obj).map(([key, value]) => (
<tr>
<td>{value.activityType}</td>
<td>{value.durationInSeconds}</td>
</tr>
)))}
</tbody>
</table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.