我正在渲染一个Flatlist,我希望根据按钮的ID是否在我的购物车中显示一个按钮。我怎么能这样做....
这是我的按钮代码:
addBtn = (id) => {
try{
let productAdded = this.state.addedToCart;
return productAdded.map((pid) => {
if (pid == id) {
// console.log(pid);
// console.log("-----------");
console.log(id + " is added into cart");
return(
<Button
key={id}
style={{
backgroundColor: '#fff',
borderWidth: 2,
borderColor: '#2e6153',
borderStyle: 'solid',
}}
>
<Text style={{color: '#2e6153',}}>Added</Text>
</Button>
);
} else {
console.log("not added to cart");
return(
<Button
key={id}
onPress={() => {
this.saveCart(id);
}}
style={{
backgroundColor: '#2e6153',
borderWidth: 2,
borderColor: '#2e6153',
borderStyle: 'solid',
width: 80,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text>Add</Text>
</Button>
);
}
});
}catch(errors){
console.log(errors);
}
}
其中“addBtn =(id)”的id来自FlatList的renderItem。
和this.state.addedToCart是我的购物车中的项目数组。目前我在购物车中添加了两个商品,所以this.state.addedToCart = [“1015”,“1016”]
和输出是:Here is the image of my output
我想只渲染一次,但按钮的渲染次数与我的购物车尺寸相同。
我猜有一个问题:
return productAdded.map((pid) => {
只需将其删除并将if语句更改为:
if (productAdded.includes(id)) {
所以它只会返回一个按钮