我有一个flatList来展示我的产品。现在,我要检查购物车中是否存在每行,并显示有多少行。
我有购物车数据和产品数据。
(适用于每个产品屏幕)
<FlatList
data={this.state.dataSource}
keyExtractor={(item, index) => String(item.id)}
extraData={this.state.dataSource}
renderItem={({item}) =>
<View style={{flex:1,height:'100%',marginTop:2,marginBottom:2}}>
//Show Title
<Text>{item.title} - {item.type}</Text>
//Show Cost
<Text>${item.cost}</Text>
//Add to cart with every Press
<TouchableOpacity onPress={() => this.setState({
productId:item.id,
productname:item.title,
productType:item.type,
productPrice:item.cost
}, this.decrementCount)} activeOpacity={0.5}>
<AntDesign name="minus" size={15}/>
</TouchableOpacity>
//Show how many is in cart
<Text>{How can I show count of product}</Text>
//Delete from cart with every Press
<TouchableOpacity onPress={() => this.setState({
productId:item.id,
productname:item.title,
productType:item.type,
productPrice:item.cost
}, this.incrementCount)} activeOpacity={0.5} style={{position:'absolute',left:48,top:10}}>
<AntDesign name="plus" size={15} style={{color:'#fff'}}/>
</TouchableOpacity>
</View>
}
/>
this.state.datacart :(产品值为类别ID)
这是我的数据车。我会检查产品是否在此列表中。
Array [
Object {
"count": "1",
"id": "413",
"name": "T-Shirt",
"price": 3000,
"product": "4",
"type": "One",
},
Object {
"count": "1",
"id": "414",
"name": "T-Shirt",
"price": 5000,
"product": "5",
"type": "Two",
},
Object {
"count": "1",
"id": "415",
"name": "T-Shirt",
"price": 3500,
"product": "1",
"type": "Three",
},
]
答案 0 :(得分:0)
您应该为购物车添加一个数组,并向其中添加新项并从中删除
bottomy
现在您可以检查购物车中的产品数量
state = { cartList: [] }
increaseCart = (product) => {
const state = this.state;
const index = state.cartList.findIndex(item => item.id == product.id);
if(index > -1) {
state.cartList[index].count = state.cartList[index].count + 1;
} else {
product.count = 1;
state.cartList.push(product);
}
this.setState( state );
}
decreaseCart = (product) => {
const state = this.state;
const index = state.cartList.findIndex(item => item.id == product.id);
if(index > -1) {
state.cartList[index].count = state.cartList[index].count - 1;
if(state.cartList[index].count <= 0)
state.cartList.splice(index, 1);
}
this.setState( state );
}
最后这将是您的renderItem:
renderCount = (product) => {
var count = 0;
const index = state.cartList.findIndex(item => item.id == product.id);
if(index > -1)
count = state.cartList[index].count;
return(
<Text>{count}</Text>
);
}