[英]React Error: Objects are not valid as a React child,If you meant to render a collection of children, use an array instead
[英]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.