[英]React.js - Cannot read property 'map' of undefined
當組件掛載時,我正在發出一個ajax請求,該請求返回帶有對象數組的Object。
getPages() {
getAllPagesData().then((pages) => {
let data = pages
this.setState({ pages });
});
}
在此功能內,我可以有效地訪問數據。
console.log(pages.pages[0].description)
打印正確的頁面描述。
在渲染中,我將state設置為變量以返回:
render() {
const pages = this.state.pages.pages
console.log(pages)
return (
chrome中的console.log是:
(55) [Object, Object, Object, Object,...
然后,我嘗試使用map遍歷數組:
return (
<div>
<Nav />
{ pages.map((post, index) => (
它會中斷頁面,錯誤是: Cannot read property 'map' of undefined at Pages.render
我嘗試了許多不同的方法來訪問該對象及其內部的數組,但是無法使單個數組項顯示在render函數中。
嘗試在render方法中使用此行
const pages = this.state.pages.pages || [ ]
這很可能是因為在ajax請求完成之前調用了render
方法。 因此, this.state.pages.pages
最初是undefined
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.