【发布时间】:2019-11-01 15:46:11
【问题描述】:
我正在尝试将从 API 调用返回的 JSON 对象数组保存到 React 中的状态(以便我可以使用这些数据来呈现表格)。我收到错误 Error: Objects are not valid as a React child (found: object with keys {street, suite, city, zipcode, geo}). If you meant to render a collection of children, use an array instead.
我不知道如何解决这个问题。看起来 JSON 应该存储在一个数组中。但是,对象内部也有嵌套对象可能会导致问题,例如:
address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
任何帮助将不胜感激。下面是我的代码:
let tableData = []
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => {
tableData = data
props.addItem(tableData)
})
这是 addItem 函数:
addItem(item) {
this.setState(function(prevState) {
return {
tables: [...prevState.tables, item]
}
})
}
更新
这是我渲染数据的方式:
App.js:
render() {
return (
<div>
{this.state.tables.map(item => {
return (<TableComponent key={item} data={item} />)
})}
</div>
)
}
TableComponent.js:
class TableComponent extends React.Component {
constructor(props){
super(props);
this.getHeader = this.getHeader.bind(this);
this.getRowsData = this.getRowsData.bind(this);
this.getKeys = this.getKeys.bind(this);
}
getKeys = function(){
return Object.keys(this.props.data[0]);
}
getHeader = function(){
let keys = this.getKeys();
return keys.map((key, index)=>{
return <th key={key}>{key.toUpperCase()}</th>
})
}
getRowsData = function(){
let items = this.props.data;
let keys = this.getKeys();
return items.map((row, index)=>{
return <tr key={index}><RenderRow key={index} data={row} keys={keys}/></tr>
})
}
render() {
return (
<div>
<table>
<thead>
<tr>{this.getHeader()}</tr>
</thead>
<tbody>
{this.getRowsData()}
</tbody>
</table>
</div>
);
}
}
const RenderRow = (props) =>{
return props.keys.map((key, index)=>{
return <td key={props.data[key]}>{props.data[key]}</td>
})
}
【问题讨论】:
-
请张贴您呈现数据的位置。当您尝试将 JavaScript 对象直接呈现到 DOM 时会发生此错误。
-
已更新以添加有关我在何处呈现数据的信息。感谢您指出这一点。
-
非常感谢@ChrisB 的评论。我无法从错误消息中看出问题出在数据的呈现中,而不是在将其保存到状态中(因为错误中引用了行号)。我发布了一个答案。