// 点击购物车事件 buttonClick(e){ // 当前商品的id号 var goodsindex=e.currentTarget.dataset.index console.log(goodsindex); // 筛选出当前选择的那个商品 // console.log(this.data.goodsList[this.properties.LeftIndex]); // 商品信息数组 let currentGoodsList = this.data.currentGoodsList; // 将点击过滤过的商品追加到currentGoodsList中 currentGoodsList.push(this.data.goodsList[this.properties.LeftIndex].filter(x => x.id === goodsindex)); // 将currentGoodsList数组赋值给data中的currentGoodsList this.setData({ currentGoodsList: currentGoodsList } ); console.log(this.data.currentGoodsList.id); //组织一个商品的信息对象 const goods={ goods_id:this.data.currentGoodsList.cmtcount, // 商品id goods_name:this.data.currentGoodsList.title, // 商品名称 goods_price:this.data.currentGoodsList.price, // 商品的价格 goods_count:1, // 商品的数量 goods_img:this.data.currentGoodsList.img, // 商品的图片 goods_state:true // 商品的勾选状态 } console.log(goods); // 将组织好的商品信息存储到store中 this.addToCart(goods) },帮我找出上述代码的bug
时间: 2024-02-05 11:04:47 浏览: 40
在代码第19行中,使用了数组的 filter 方法来过滤出当前选择的商品,但是 filter 方法的返回值是一个数组,而不是单个对象。因此,在第23行中,将该数组 push 到 currentGoodsList 数组中会导致 currentGoodsList 中存储的是一个嵌套数组,而不是单个对象。因此,需要将 filter 方法返回的数组中的第一个元素作为当前选择的商品对象,而不是直接将数组 push 到 currentGoodsList 数组中。修改代码如下:
```
// 点击购物车事件
buttonClick(e){
// 当前商品的id号
var goodsindex=e.currentTarget.dataset.index
console.log(goodsindex);
// 商品信息数组
let currentGoodsList = this.data.currentGoodsList;
// 筛选出当前选择的那个商品,并将其作为单个对象存储到 currentGoodsList 中
currentGoodsList.push(this.data.goodsList[this.properties.LeftIndex].find(x => x.id === goodsindex));
// 将currentGoodsList数组赋值给data中的currentGoodsList
this.setData({
currentGoodsList: currentGoodsList
});
console.log(this.data.currentGoodsList.id);
//组织一个商品的信息对象
const goods={
goods_id:this.data.currentGoodsList.cmtcount, // 商品id
goods_name:this.data.currentGoodsList.title, // 商品名称
goods_price:this.data.currentGoodsList.price, // 商品的价格
goods_count:1, // 商品的数量
goods_img:this.data.currentGoodsList.img, // 商品的图片
goods_state:true // 商品的勾选状态
}
console.log(goods);
// 将组织好的商品信息存储到store中
this.addToCart(goods)
}
```