首页 > 解决方案 > 我不断收到此错误 Objects are not valid as a React child {} 如果您要呈现子集合,请改用数组

问题描述

这就是我的代码目前的样子

import React from 'react';
import './App.css';

class App extends React.Component {
 
  state = {
  apiData: []
  }
 
  render() {   
    
  console.log('api data is')
    return (
      <div>
        <center>
        <h1 id="title">hello something</h1></center>
        <h1 id="date">{this.state.apiData.title}</h1>
      </div>
    )
  }
 
  componentDidMount() {
    fetch('http://www.mocky.io/v2/5dece3d333000052002b9037')
      .then(response => response.json())
      .then(data => {
        this.setState({
          apiData: data
        })
      })        
      console.log("component fetched data")
  }
}
 
export default App

当我尝试访问具有价值的东西但是当我这样做时,我得到了这个错误

     <h1 id="date">{this.state.apiData.date}</h1>

有用

不太确定如何解决,因为到目前为止我所看到的所有内容都是针对他们通过 const 或 let 创建的数据,而不是从 API 获取数据

标签: javascriptreactjs

解决方案


apiData.title是 type Object,而不是ArrayJSX 子节点或字符串。

您需要使用apiData.title.rendered,如来自 API 的响应数据片段所示:

  "title": {
    "rendered": "Whatsapp and Facebook Messenger: how group chat is changing the dynamic of our friendships"
  },

推荐阅读