Reputation: 2266
I have a React state that looks like so:
state = {
itemList: []
};
I have a render function that looks like this:
render() {
return (
<div className="App">
<ListingContainer itemList={this.state.itemList} />
</div>
);
};
The ListingContainer
component looks like this:
const ListingContainer = (itemList) => {
return(
<div>
{
// getting type error, itemList.map is not a function
itemList.map(({data}) => <Item data={data} />)
}
</div>
);
};
And I'm setting my state as follows:
componentWillMount() {
// getList promise is confirmed to be providing an array
this._asyncRequest = getList().then(
itemList => {
this._asyncRequest = null;
// breakpoint confirms itemList is array at this time
this.setState({itemList});
}
);
}
A breakpoint placed just before the itemList.map
call shows that itemList is actually an object containing the actual itemList array that I'm looking for, like so:
itemList:
{
itemList: [ ... ]
}
Instead of what I expect, which would be:
itemList:
[ ... ]
Why is my array being trasformed into a self-titled object that contains my array?
Upvotes: 0
Views: 47
Reputation: 2483
In React, if you pass props to a functional component as <ListingContainer itemList={this.state.itemList} />
it will be accessible inside an object called props or anything you named it.
Here const ListingContainer = (itemList) => {...}
you have named that object as itemList
. That's why you are getting the result itemList.itemList = [ ... ]
.
So, you can change your code i.e. use destructuring as {itemList}
const ListingContainer = ({itemList}) => {
return(
<div>
{
// getting type error, itemList.map is not a function
itemList.map(({data}) => <Item data={data} />)
}
</div>
);
};
or without destructuring
const ListingContainer = (props) => {
return(
<div>
{
props.itemList.map(({data}) => <Item data={data} />)
}
</div>
);
};
Upvotes: 3