1

我正在制作一个电子商务反应本机应用程序,并且在应用程序的 CART 部分中,我希望添加到购物车中的具有相同 ID(您可以在控制台中看到的类别 ID)中的每个项目只呈现一次,但在我的情况下如果我在购物车中添加 3 个具有相同 id 的项目,我将看到 3 个不同的 listItems 他们尊重的项目。如果有多个具有相同 ID 且数量增加的项目,我希望我的地图功能显示 1 个列表项。到目前为止,我的代码只是将每个选定的产品呈现为一个单独的项目:

renderItems() {
let items = [];
this.state.cartItems.map((item, i) => {
  console.log(item)
  items.push(
    <ListItem
      key={i}
      last={this.state.cartItems.length === i + 1}
      onPress={() => this.itemClicked(item)}
    >
      <Thumbnail square style={{ width: 100, height: 100 }} source={{ uri: item.productdetail.image }} />
      <Body style={{ paddingLeft: 10 }}>
        <Text style={{ fontSize: 16 }}>

          {item.productdetail.name}

        </Text>

        <Text style={{ fontSize: 14, fontStyle: 'italic' }}>Price: {item.productdetail.price}</Text>
        <Text style={{ fontSize: 14, fontStyle: 'italic' }}>Quantity: {item.quantity > 1 ? item.quantity : 1}</Text>

      </Body>
      <Right>
        <Button style={{ marginLeft: -25 }} transparent onPress={() => this.removeItemPressed(item)}>
          <Icon size={30} style={{ fontSize: 30, color: '#95a5a6' }} name='ios-remove-circle-outline' />
        </Button>
      </Right>
    </ListItem>
  );
});
return items;}

console.log 的结果如下 在此处输入图像描述

这就是我的购物车的样子 在此处输入图像描述

现在你可以看到购物车应该只显示一个具有相同产品的 listItem 数量=18

4

2 回答 2

1

考虑到您有一个像这样的简单数据集:

const rawItemsData = [
    {id: 1, qty: 2},
    {id: 1, qty: 3},
    {id: 2, qty: 1},
    {id: 1, qty: 2},
    {id: 2, qty: 5},
    {id: 3, qty: 6}
];

如果要获取具有唯一项目 ID 和总数量的数组,可以使用 reduce :

const uniqueItemsData = rawItemsData.reduce((prev, item) => {
    const existingItem = prev.find(({id}) => id === item.id);
    if(existingItem)
        existingItem.qty = existingItem.qty + item.qty;
    else
        prev.push(item);
   return prev;
 }, []); //-> [ { id: 1, qty: 7 }, { id: 2, qty: 6 }, { id: 3, qty: 6 } ];


 //Then you can use your code : 
 uniqueItemsData.map((item, id) => {
     //..
 });
于 2018-08-10T08:02:16.960 回答
0

在这种情况下,您必须在推送之前进行简单的控制,无论该项目是否存在。由你来设计它:

例如,您可以创建另一个包含唯一项目的列表。在这样的页面中,我相信保存独特的项目很有用,您可能在其他地方也需要相关信息。而且这个列表不应该需要 setState 因为它只是为了控制。

this.state.uniqueItems = [];

在每次推送中,将项目添加到 uniqueItems。此处不要使用 setState,因为它会导致冗余渲染:

this.state.uniqueItems.push(item);

在 map 函数中,在推送之前,检查它的 id 是否存在于唯一列表中。您可以在此处使用简单的 for 循环、lodash 库或 Array 的 find 方法。

于 2018-08-10T08:00:14.840 回答