javascript - 我不断收到此错误 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 获取数据
解决方案
apiData.title
是 type Object
,而不是Array
JSX 子节点或字符串。
您需要使用apiData.title.rendered
,如来自 API 的响应数据片段所示:
"title": {
"rendered": "Whatsapp and Facebook Messenger: how group chat is changing the dynamic of our friendships"
},
推荐阅读
- azure - 使用应用程序洞察力的自定义应用程序仪表板
- google-data-studio - 使用 PATH_USER_PASS 的身份验证类型时不调用 getData()
- java - 结合使用 java 流的操作
- javascript - replaceText Google Apps 脚本将空白值传递给 Google Doc Merge
- python - 如何将'conans' python 包安装到系统中?
- react-native - React Native expo-cli 找不到模块 expo.js
- javascript - 如何跟踪单个 JavaScript 进程?
- reactjs - React 组件在“状态或道具变化”或“每个状态变化”上重新渲染,混淆官方文档
- r - 具有未知数量和变量名称的数据集上的多个 QQ 图
- javascript - 从现有的 js 对象创建另一个不同格式的 js 对象