gpt4 book ai didi

javascript - 使用 ReactJS 在表中渲染多个表行和多个表数据

转载 作者:行者123 更新时间:2023-12-03 01:25:47 25 4
gpt4 key购买 nike

嗨,我想要有多个 TR,并且在一个 TR 中,使用 React 有多个 TD 我想循环遍历我的 ComparisonProperties 对象并在渲染方法中动态创建表,但我收到此错误:

Uncaught Error: Objects are not valid as a React child (found: object with keys {id, address, long, lat, cityId, cityDistrict, phone,
name, userId, city})
. If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Comparison.

我的数据对象是这样的,我无法改变它的结构:

       //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);

更新答案:

所以我找出了问题所在,但我从 react 中得到了更好的错误消息问题是在我的compareProperties中,我在数组中有一个对象导致了错误

    let comparedProperties = {"id":[101,102],"estateAgency":[{"id":1},{"id":2}]}

最佳答案

Edit 50o29v2vok

你想做类似的事情吗?

  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>
)
}

关于javascript - 使用 ReactJS 在表中渲染多个表行和多个表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51553131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com