简体   繁体   English

React.js-无法读取未定义的属性“ map”

[英]React.js - Cannot read property 'map' of undefined

When the component mounts, I'm making an ajax request that returns an Object with an array of objects. 当组件挂载时,我正在发出一个ajax请求,该请求返回带有对象数组的Object。

getPages() {
  getAllPagesData().then((pages) => {
    let data = pages
    this.setState({ pages });
  });
}

Inside this function I can access the data effectively. 在此功能内,我可以有效地访问数据。

console.log(pages.pages[0].description)

Prints the correct page description. 打印正确的页面描述。

In render I'm setting state to a variable to access in my return: 在渲染中,我将state设置为变量以返回:

render() {

  const pages = this.state.pages.pages
  console.log(pages)

return (

That console.log in chrome is: chrome中的console.log是:

(55) [Object, Object, Object, Object,...

I'm then trying to iterate through the array using map: 然后,我尝试使用map遍历数组:

return (
  <div>
    <Nav />
     { pages.map((post, index) => (

It breaks the page and the error is: Cannot read property 'map' of undefined at Pages.render 它会中断页面​​,错误是: Cannot read property 'map' of undefined at Pages.render

I've tried many different ways to access this object and the array inside of it, but cannot get individual array items to display inside the render function. 我尝试了许多不同的方法来访问该对象及其内部的数组,但是无法使单个数组项显示在render函数中。

Try using this line in the render method 尝试在render方法中使用此行

const pages = this.state.pages.pages || [ ]

It is most likely because the render method is called before the ajax request is complete. 这很可能是因为在ajax请求完成之前调用了render方法。 So the this.state.pages.pages is undefined initially. 因此, this.state.pages.pages最初是undefined

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

相关问题 React.js - “无法读取未定义的属性‘地图’” - React.js - “Cannot read property 'map' of undefined” 错误:无法读取未定义 React.JS 的属性“map” - Error : Cannot read property 'map' of undefined React.JS 无法读取未定义 [React.js] 的属性“地图” - Cannot read property 'map' of undefined [React.js] TypeError:无法读取 react.js 中未定义的属性“地图” - TypeError: Cannot read property 'map' of undefined in react.js React.js 错误:TypeError:无法读取未定义的属性“地图” - React.js error :TypeError: Cannot read property 'map' of undefined TypeError:无法读取未定义React.js的属性“ map” - TypeError: Cannot read property 'map' of undefined React.js “无法读取未定义(React.js)的属性&#39;map&#39;” - “Cannot read property 'map' of undefined (React.js)” TypeError:无法读取React.js上未定义的属性&#39;map&#39; - TypeError: Cannot read property 'map' of undefined on React.js 函数返回数据以过滤和映射显示错误 React.js TypeError:无法读取未定义的属性“val” - function returning the data to filter and map that show error React.js TypeError: Cannot read property 'val' of undefined TypeError:无法读取 Netlify CMS/React.js 上未定义的属性“地图” - TypeError: Cannot read property 'map' of undefined on Netlify CMS/React.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM