说明
例如:当小程序调用扫码扫描设备二维码时,展示相关套餐,同时会把码内的id存成缓存。以确保切换到其他页面回来后套餐还在。把请求套餐的接口放在onShow里面就行。但同时使用微信扫码进入的时候一般会在onLoad里面调用。这样就会出现每次进入这个页面会调用两次套餐的接口。预期结果:只调用一次接口
要解决这个问题,我们可以通过设置一个标志位来控制getList()函数的调用。在onLoad函数中,我们可以设置一个标志位来表示是否已经调用了getList()函数。在onShow函数中,我们检查这个标志位以及equipment_id是否存在,如果两者都满足,就不调用getList()函数。这样可以确保即使页面被重新展示,getList()函数也只会被调用一次。
// 在data中定义一个标志位
data() {
return {
// ...其他数据
isEquipmentInfoFetched: false, // 是否已经获取过设备信息
};
},
onLoad(options) {
this.getshuju() // 轮播图
this.getTips() // 注意事项
this.getAd()
if (options.sn) {
uni.setStorageSync('equiId', options.sn);
this.equipment_id = options.sn
this.getList() // 套餐
this.isEquipmentInfoFetched = true; // 设置标志位
return
}
// #ifdef MP-WEIXIN
if (options.q) {
let url = decodeURIComponent(options.q)
this.equipment_id = this.$common.getUrlKey('sn', url)
uni.setStorageSync('equiId', this.equipment_id);
this.getList() // 套餐
this.isEquipmentInfoFetched = true; // 设置标志位
return
}
// #endif
// #ifdef MP-ALIPAY
if (getApp().globalData.sn) {
this.equipment_id = getApp().globalData.sn;
uni.setStorageSync('equiId', this.equipment_id);
this.getList() // 套餐
this.isEquipmentInfoFetched = true; // 设置标志位
return
}
// #endif
},
onShow() {
this.equipment_id = uni.getStorageSync('equiId')
if (this.equipment_id && !this.isEquipmentInfoFetched) {
this.getList() // 套餐
this.isEquipmentInfoFetched = true; // 设置标志位
}
},
这样,无论是在onLoad还是onShow中,只要getList()函数被调用过,isEquipmentInfoFetched标志位就会被设置为true,这样在onShow中就不会再次调用该函数。如果用户跳转到其他页面再返回,由于isEquipmentInfoFetched已经是true,函数不会被重复调用。如果需要重新获取设备信息,可以通过某种逻辑重置isEquipmentInfoFetched标志位。