晚安,读者们!
我正在使用React和Redux开发一个简单的购物车单页应用程序!
就是这种情况:
listOfCategories: ["Basic", "Hardware"]
listOfItems : [
{
fields: {
category: "Basic",
name: "Starter",
...
},
...
},
{
fields: {
category: "Basic",
name: "Entertainment",
...
},
...
},
{
fields: {
category: "Hardware",
name: "STB",
...
},
...
}
]
在我的组件的render方法中,有:
render() {
return (
<div>
<div>
Catalog
{this.props.listOfItems.map(item => (
<Product
id={item.fields.productexternalid}
name={item.fields.productname}
category={item.fields.SKYDE_Product_Category__c}
clicked={() => this.addToCart(item)}
costOneTime={item.fields.baseonetimefee}
costRecurring={item.fields.baserecurringcharge}
eligible={item.fields.eligible}
visible={item.fields.visible}
></Product>
))}
</div>
</div>
);
}
结果是这样的:
我只想渲染一个手风琴,其中填充了类别名称,手风琴下按类别分组的项目:
基本-> item.category
开始-> item.name
娱乐-> item.name
硬件-> item.category
STB-> item.name
.map()和.filter()函数将很有用,但我真的不知道如何处理这种情况。
任何帮助将不胜感激!
答案 0 :(得分:1)
基本
cae
硬件
<div>
Basic
{this.props.listOfItems.filter(item => item.fields.category ==="Basic").map(item => (
<Product
id={item.fields.productexternalid}
name={item.fields.productname}
category={item.fields.SKYDE_Product_Category__c}
clicked={() => this.addToCart(item)}
costOneTime={item.fields.baseonetimefee}
costRecurring={item.fields.baserecurringcharge}
eligible={item.fields.eligible}
visible={item.fields.visible}
></Product>
))}
</div>
答案 1 :(得分:1)
map()
和filter()
在这种情况下绝对有用。
render() {
// in case "listOfCategories" is not predefined
let listOfCategories = listOfItems.map(item => item.fields.category)
// sort and remove duplicates
listOfCategories = listOfCategories.sort().filter((v, i) => listOfCategories.indexOf(v) === i);
return (
<div>
{listOfCategories.map(cat => (
// You probably had this `Category` component around
<Category key={cat} name={cat} {...catProps}>
{listOfItems.filter(item => item.fields.category === cat).map(item => (
<Product
key={item.fields.id}
id={item.fields.id}
name={item.fields.name}
{...itemProps}
/>
))}
</Category>
))}
</div>
);
}