繁体   English   中英

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

[英]I keep getting this error Objects are not valid as a React child {} If you meant to render a collection of children, use an array instead

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

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 获取数据

apiData.title的类型是Object ,而不是 JSX 子节点或字符串的Array

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

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

尝试使用 null 检查{this.state.apiData.title?.rendered}

更新:尝试打开您从中获取数据的链接并按照里面的路径,对于 hero_image 您需要{this.state.apiData.acf?.hero_image.url}

由于在 state 设置之前渲染火灾,因此您需要在 state 更新和使用条件之前检查或“this.state.apiData.title”上的 && 像这样

 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 && this.state.apiData.title.rendered}</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") } } ReactDOM.render( <App />, document.getElementById('root'));
 <div id="root" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM