【问题标题】:How to save an array of JSON objects (with nested objects) to state in React如何保存 JSON 对象数组(带有嵌套对象)以在 React 中声明
【发布时间】: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 的评论。我无法从错误消息中看出问题出在数据的呈现中,而不是在将其保存到状态中(因为错误中引用了行号)。我发布了一个答案。

标签: json reactjs state


【解决方案1】:

错误消息让我离开这里,因为它看起来问题在于将对象保存为状态。但是,正如 cmets 中所指出的,错误发生在渲染过程中。为了解决这个问题,我将 RenderRow 更改为以下内容:

const RenderRow = (props) =>{
  return props.keys.map((key, index)=>{
    return <td key={props.data[key]}>{typeof props.data[key] === "object" ? JSON.stringify(props.data[key]) : props.data[key]}</td>
  })
}

具体来说,我改的部分是先检查特定元素是否为对象,如果是,则使用JSON.stringify()将其转换为字符串,然后再渲染到屏幕上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 2019-08-11
    • 2021-10-13
    • 2021-12-29
    • 2019-10-28
    • 2014-01-30
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多