我试图映射一个在react中有2层深度的对象,但我似乎无法让它在我的生命中工作。
有人能帮我一把吗?
loadBeers() {
const { userData } = this.props;
if (userData.location) {
Object.keys(userData.location).map(locationitem => {
Object.keys(userData.location[locationitem].beer).map(beerItem => {
return (
<BeerItem key={beerItem}>{userData.location[locationitem].beer[beerItem].beerName}</BeerItem>
);
});
});
} else {
return 'hi';
}
}
这是对象结构:
发布于 2018-07-26 03:47:34
您需要从第一个map()
调用中返回一些内容。如果不这样做,那么映射的结果将只是一个空数组。此外,您似乎没有返回地图的结果,但您可能正计划对其执行其他操作:
loadBeers() {
const { userData } = this.props;
if (userData.location) {
// also return result to original caller of loadBeers()
return Object.keys(userData.location).map(locationitem => {
/* Return something here from map callback */
return Object.keys(userData.location[locationitem].beer).map(beerItem => {
return (
<BeerItem key={beerItem}>{userData.location[locationitem].beer[beerItem].beerName}</BeerItem>
);
});
});
} else {
return 'hi';
}
}
下面是一个包含简单数据的配对示例:
let userData = {location :{randoKey: {beer: {anotherweridKey:{ABV: 'some_abv',beerName: 'Bud',beerType: 'bad'}}}}}
let matrix
if (userData.location) {
matrix = Object.keys(userData.location).map(locationitem => {
return Object.keys(userData.location[locationitem].beer).map(beerItem => {
return userData.location[locationitem].beer[beerItem].beerName
});
});
} else {
console.log('hi');
}
console.log(matrix)
https://stackoverflow.com/questions/51526391
复制相似问题