优化这段代码” data: { goodsObj: {}, goods_id: null}, onLoad({ goods_id }) { console.log(goods_id); this.setData({ goods_id }); this.getGoodsDetail(); }, async getGoodsDetail() { try { const { goods_id } = this.data; const [goodsObj] = await Promise.allSettled([ request({ url: "/goods/detail", data: { goods_id } }) ]); if (goodsObj.status === "fulfilled") { console.log(goodsObj.value); this.setData({ goodsObj: goodsObj.value }); this.setData({ goodsObj: { goods_name: goodsObj.value.goods_name, goods_price: goodsObj.value.goods_price, goods_introduct: goodsObj.value.goods_introduct.replace(/\.webp/g,'.jpg'), pics: goodsObj.value.pics } }); } else { throw new Error(goodsObj.reason); } } catch (error) { console.error(error); // 处理错误的方式,例如提示用户网络异常等信息 }}, handlePreviewImage(){ // console.log("预览"); const urls = this.GoodsInfo.pics.map(v=>v.pics_mid); wx.previewImage({ current:urls[0], urls: urls, }) } })“
时间: 2023-12-22 22:02:41 浏览: 77
可以优化的地方如下:
1. 使用async/await异步请求数据,可以避免回调地狱和提高代码可读性;
2. 使用try/catch捕获异步请求时的错误,提高代码的健壮性;
3. 对获取到的商品详情进行处理,只保留需要用到的字段,避免不必要的数据传输和占用存储空间。
4. 在setData时,可以将需要修改的属性整合成一个对象一次性进行修改,避免多次setData。
优化后的代码如下:
```js
data: {
goodsObj: {},
goods_id: null
},
onLoad({ goods_id }) {
console.log(goods_id);
this.setData({ goods_id });
this.getGoodsDetail();
},
async getGoodsDetail() {
try {
const { goods_id } = this.data;
const [goodsObj] = await Promise.allSettled([
request({ url: "/goods/detail", data: { goods_id } })
]);
if (goodsObj.status === "fulfilled") {
console.log(goodsObj.value);
const goodsData = goodsObj.value;
const newData = {
goods_name: goodsData.goods_name,
goods_price: goodsData.goods_price,
goods_introduct: goodsData.goods_introduct.replace(/\.webp/g,'.jpg'),
pics: goodsData.pics
};
this.setData({ goodsObj: newData });
} else {
throw new Error(goodsObj.reason);
}
} catch (error) {
console.error(error);
// 处理错误的方式,例如提示用户网络异常等信息
}
},
handlePreviewImage() {
const { pics } = this.data.goodsObj;
const urls = pics.map(v => v.pics_mid);
wx.previewImage({
current: urls[0],
urls: urls,
});
}
```
阅读全文