I cant map array of objects eventhough it's printed in console.log

邮差的信 提交于 2021-01-27 21:14:32

问题


I'm trying to map an array of objects but it keeps saying that docs are undefined even though I can clearly see it in console.log

This is what I get when I console.log

{console.log(this.props.results.data)} 

what I want is in the docs field. If I expand it looks like this

Since I want to print out the content of docs this is what I tried doing

<div className='list-render'>
   {this.props.results.loading ? <LoadingSpinner/> : 
      <div className='row'>
         {(this.props.results.data.docs.map((data) => { // code to print individual fields )}
      </div>
   </div>}
</div> 

I get TypeError: this.props.results.data.docs is undefined I'm using mongoose-paginate-v2 library for pagination


回答1:


You need to check if the docs property is not undefined. You can do that in a couple of ways:

  1. You can use optional chaining to check if the property is not null or undefined. Then your code will look like this this.props.results.data?.docs.map.... Here's how you add it to your react app (but if you are using the latest babel version - it should work out of the box)

  2. You do the check yourself. The most basic one is, as suggested in the comment, is to check if the property is falsy:

this.props.results.data.docs && this.props.results.data.docs.map((data)

The comment is a bit incorrect though, you don't need to check if data is falsy (only if the error is pointing at that), you check if docs is falsy.



来源:https://stackoverflow.com/questions/62508331/i-cant-map-array-of-objects-eventhough-its-printed-in-console-log

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!