问题
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:
You can use optional chaining to check if the property is not
null
orundefined
. Then your code will look like thisthis.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)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