嗨,我想拥有多个TR,并在其中包含多个TD,我想遍历我的compareProperties对象并在render方法中动态创建表,但出现此错误:
未捕获的错误:对象作为React子
(found: object with keys {id, address, long, lat, cityId, cityDistrict, phone, name, userId, city})
无效。如果您打算呈现一个 子代,使用数组代替或使用 来自React附加组件的createFragment(object)。检查渲染方法 比较。
我的数据对象就是这样,我无法更改其结构:
//this is a samle data, keys in this object can dynamically change elsewhere
let comparedProperties = {
id: [1001,1002],
address: ["abc","def"],
};
这是我的代码:
class Comparison extends Component {
render() {
let comparedProperties = {
id: [1001, 1002],
address: ["abc", "def"]
};
let comparedItemsData = [];
for (var key in comparedProperties) {
if (comparedProperties.hasOwnProperty(key)) {
let newTR = <tr key={Math.random()} className="compare-table-row">
<td className="table-item-header">
{key}
</td>
{comparedProperties[key].map((item) => {
return <td key={Math.random()} className="table-item">{item}</td>;
})}
</tr>;
comparedItemsData.push(newTR)
}
}
return (
<table className="compare-table">
<tbody>
{comparedItemsData}
</tbody>
</table>
)
}
}
const mapStateToProps = (state) => ({
...state
});
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(Actions, dispatch)
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Comparison);
更新答案:
所以我想知道问题出在哪里,但我从反应中得到了更好的错误信息 问题是在我的compareProperties中,数组中有一个导致错误的对象
let comparedProperties = {"id":[101,102],"estateAgency":[{"id":1},{"id":2}]}
答案 0 :(得分:0)
您只需要从map函数中返回td
元素。同样也不要指定Math.random()
作为react元素的键,因为每次调用render都会分配一个新的键,即使没有任何改变,它也会迫使React重新渲染整个组件。
for (var key in comparedProperties) {
if (comparedProperties.hasOwnProperty(key)) {
let newTR = <tr key={key} className="compare-table-row">
<td className="table-item-header">
{key}
</td>
//comparedProperties[key] is an array of
// values that I want to make them as td elements
{ comparedProperties[key].map((item) => {
return <td key={item} className="table-item">{item}</td>;
})}
</tr>;
comparedItemsData.push(newTR)
}
}
答案 1 :(得分:0)
您是否正在尝试做类似的事情?
render(){
let comparedProperties = {
id: [1001, 1002],
address: ["abc", "def"],
};
return (
<table>
{Object.keys(comparedProperties).map(key=>(
<tr key={Math.random()} className="compare-table-row">
<td className="table-item-header">
{key}
</td>
{comparedProperties[key].map((item) => (
<td key={Math.random()} className="table-item">{item}</td>
))}
</tr>
))}
</table>
)
}
或者,如果您想尝试作为无状态补偿,请在表格中插入:
const ComparedItemsData = ({ comparedProperties }) =>(
<React.Fragment>
{Object.keys(comparedProperties).map(key => (
<tr key={Math.random()} className="compare-table-row">
<td className="table-item-header">{key}</td>
{comparedProperties[key].map(item => (
<td key={Math.random()} className="table-item">
{item}
</td>
))}
</tr>
))}
</React.Fragment>
)
const App = ()=>{
let comparedProperties = {
id: [1001, 1002],
address: ["abc", "def"]
};
return (
<table className="compare-table">
<tbody>
<ComparedItemsData comparedProperties={comparedProperties}/>
</tbody>
</table>
)
}