[英]How to render data from a API response in a table using react js
我正在尝试在表中获取 API 响应数据。 我从 API 获得的数据是动态的,也就是说,当我运行 API 时,它总是会发生变化,所以键和值会发生变化我得到的数据正是下面这种格式
{D1:[真,真,假],D2:[假,真,真],D3:[真,假]}
在这里,我希望 D1、D2、D3 作为列标题,将值作为行这里是我希望这些数据看起来如何的示例
D1。 | D2。 | D3。 |
---|---|---|
真的 | 错误的 | 真的 |
真的 | 真的 | 错误的 |
错误的 | 真的 |
每次运行后,从 header 到行的数据都会发生变化。 我刚刚获取了 API 并在 state 中设置了响应,我只是不知道如何在表中使用该数据。 先感谢您。
{
const [Data, setData]=useState("")
let RunScript = async(e) =>{
e.preventDefault();
fetch('http://localhost:5000/getresult',{
method: "POST",
crossDomain: true,
header: {
"Content-Type":"application/json",
},
body:JSON.stringify({
UserInput
}),
}).then((response)=>response.json())
.then(data=>{
console.log(data)
setData(data);
})
}
}
没有做任何造型,只是功能。
<table border={1}>
<thead>
<tr>
{Object.keys(Data).map((item) => {
return <th key={item}>{item}.</th>;
})}
</tr>
</thead>
<tbody>
{[
...Array(
Math.max(...Object.values(Data).map((item) => item.length))
),
].map((itm, idx) => {
return (
<tr>
{Object.values(Data).map((item) => {
return (
<td>
{typeof item[idx] === "boolean"
? new Boolean(item[idx]).toString()
: ""}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
你可以做这样的事情
import "./styles.css";
export default function App() {
const Data = {
D1: [true, true, false],
D2: [false, true, true],
D3: [true, false],
};
const maxRowLenght = Math.max(
...Object.values(Data).map((item) => item.length)
);
return (
<table>
<thead>
<tr>
{Object.keys(Data).map((item) => {
return <th key={item}>{item}.</th>;
})}
</tr>
</thead>
<tbody>
{[...Array(maxRowLenght)].map((element, index) => {
return (
<tr>
{Object.values(Data).map((item) => {
return (
<td>
{typeof item[index] === "boolean"
? item[index].toString()
: ""}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.