【发布时间】:2022-01-13 11:34:56
【问题描述】:
到目前为止,我的代码运行良好。直到我不得不修改数据文件并在其中创建一个嵌套数组。我收到 错误:对象作为 React 子对象无效(找到:带有键 {one、B、C、D、E、G、H、I、L、M、N、P、Q、 R,S})。如果您打算渲染一组子项,请改用数组。
下面是我的表格组件
import React from "react";
import tableData from "./tableData1.js";
const TableComponent = ({ data }) => {
let headings = Object.keys(data[0]);
return (
<table className="table table-dark table-striped">
<thead>
<tr>
<th colspan="16">Dimensions in mm</th>
</tr>
<tr scope="col">
<th>Series</th>
{headings.map((heading) => (
<th>{heading}</th>
))}
</tr>
</thead>
<tbody>
{data.map((item) => (
<tr scope="col">
<th scope="row">Series No.</th>
{headings.map((heading) => (
<td>{item[heading]}</td>
))}
</tr>
))}
</tbody>
</table>
);
};
const TableGenerator = ( {targetID} ) => {
const filteredData = tableData.filter(item => item.id == targetID ).map(item => item.value);
return <TableComponent data={filteredData} />;
};
export default TableGenerator;
这是目前仅使用一些模拟数据进行测试的数据文件。
const tableData1 = [
{
id: 1,
value: [
{
one: "Value",
B: "Value",
C: "Value",
D: "Male",
E: "Value",
G: "Value",
H: "Value",
I: "Value",
L: "Value",
M: "Value",
N: "Value",
P: "Value",
Q: "Value",
R: "Value",
S: "Value",
},
{
one: "Value",
B: "Value",
C: "Value",
D: "Male",
E: "Value",
G: "Value",
H: "Value",
I: "Value",
L: "Value",
M: "Value",
N: "Value",
P: "Value",
Q: "Value",
R: "Value",
S: "Value",
},
],
},
{
id: 2,
value: [
{
two: "Value",
B: "Value",
C: "Value",
D: "Male",
E: "Value",
G: "Value",
H: "Value",
I: "Value",
L: "Value",
M: "Value",
N: "Value",
P: "Value",
Q: "Value",
R: "Value",
S: "Value",
},
{
two: "Value",
B: "Value",
C: "Value",
D: "Male",
E: "Value",
G: "Value",
H: "Value",
I: "Value",
L: "Value",
M: "Value",
N: "Value",
P: "Value",
Q: "Value",
R: "Value",
S: "Value",
},
],
}
]
以前我的格式如下:
const tableData1 = [
{
id: 1,
value:
{
one: "Value",
B: "Value",
C: "Value",
D: "Male",
E: "Value",
G: "Value",
H: "Value",
I: "Value",
L: "Value",
M: "Value",
N: "Value",
P: "Value",
Q: "Value",
R: "Value",
S: "Value",
}
},
{
id: 2,
value:
{
two: "Value",
B: "Value",
C: "Value",
D: "Male",
E: "Value",
G: "Value",
H: "Value",
I: "Value",
L: "Value",
M: "Value",
N: "Value",
P: "Value",
Q: "Value",
R: "Value",
S: "Value",
}
}
]
我猜我必须以不同的方式映射它或按照这些思路进行映射,但无论我在哪里看,我似乎都无法绕开它。任何人都可以帮助解决这个问题?
【问题讨论】:
-
我不知道应该使用哪种类型,模拟还是以前的数据?
-
const filtersData = tableData.filter(item => item.id == targetID).map(item => item.value);在map方法中每一项是:[ { one: "Value", B: "Value", C: "Value", D: "Male", ...}, { one: "Value", B: "Value ", C: "Value", D: "Male", ...}] 所以你需要另一个映射到每个元素,为什么你可能需要重复的对象?
-
将值视为已从单例对象变为对象数组。您现在不想渲染多个 TableComponent 吗?.. 因为 TableComponent 需要一个对象,而不是一个数组..
-
@Vencovsky 我首先共享的模拟数据是我需要它工作的地方,因为它已经在第二个工作了。
-
@Ebay 我基本上想要实现的是 Object.keys 旨在让我从值数组中的每个对象中获取所有标题,其余代码旨在生成行根据这些标题(属性)的值在这些标题下,如果有任何意义的话。
标签: javascript reactjs object frontend syntax-error