简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM