我正在渲染一个 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)) {
所以它只会返回一个按钮
关于javascript - 如何比较两个数组的值,如果两者相等或不返回差异。按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55880936/