TypeError:尝试在React中动态生成表时,无法将未定义或null转换为对象



我正试图根据表获得的数据动态地呈现它。这个部分是有效的,但是当我实现数据的过滤版本时,我在let headings = Object.key(data[1])行上得到了TypeError Undefined或Null to object错误。

import React from "react";
import tableData from "./tableData1.js";
const TableComponent = ({ data }) => {
**let headings = Object.keys(data[1]);** //This is where I get the Error
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 = () => {
const filteredData = tableData.filter(item => item.id == 1).map(item => item.value);
return <TableComponent data={filteredData} />;
};
export default TableGenerator;

以下是供参考的数据(目前只是一些模拟数据(:

const tableData1 = [
{
id: 1,
value: {
A: "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: {
A: "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: 3,
value: {
A: "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",
}
},
];
export default tableData1;

在我添加const filteredData部分之前,它就已经工作了,我正在将tableData直接传递给TableComponent,我不知道为什么。有人能帮我吗?

您收到此错误是因为data[1];返回未定义,因此Object.keys()无法使用。

这可能意味着您的filteredData被过滤错误,或者您在错误的索引处访问它。

最新更新