教你解决showLoading 和 showToast显示异常的问题

本文介绍了如何在微信小程序中解决showLoading和showToast相互覆盖的问题,通过自定义API并设置优先级,确保网络请求失败时正确显示错误信息。

问题描述

当wx.showLoading 和 wx.showToast 混合使用时,showLoading和showToast会相互覆盖对方,调用hideLoading时也会将toast内容进行隐藏。

触发场景

当我们给一个网络请求增加Loading态时,如果同时存在多个请求(A和B),如果A请求失败需要将错误信息以Toast形式展示,B请求完成后又调用了wx.hideLoading来结束Loading态,此时Toast也会立即消失,不符合展示一段时间后再隐藏的预期。

解决思路

这个问题的出现,其实是因为小程序将Toast和Loading放到同一层渲染引起的,而且缺乏一个优先级判断,也没有提供Toast、Loading是否正在显示的接口供业务侧判断。所以实现的方案是我们自己实现这套逻辑,可以使用Object.defineProperty方法重新定义原生API,业务使用方式不需要任何修改。

代码参考

// 注意此代码应该在调用原生api之前执行
let isShowLoading = false;
let isShowToast = false;
const {
  showLoading,
  hideLoading,
  showToast,
  hideToast
} = wx;
Object.defineProperty(wx, 'showLoading', {
  configurable: true, // 是否可以配置
  enumerable: true, // 是否可迭代
  writable: true, // 是否可重写
  value(...param) {
    if (isShowToast) { // Toast优先级更高
      return;
    }
    isShowLoading = true;
    console.log('--------showLoading--------')
    return showLoading.apply(this, param); // 原样移交函数参数和this
  }
});
Object.defineProperty(wx, 'hideLoading', {
  configurable: true, // 是否可以配置
  enumerable: true, // 是否可迭代
  writable: true, // 是否可重写
  value(...param) {
    if (isShowToast) { // Toast优先级更高
      return;
    }
    isShowLoading = false;
    console.log('--------hideLoading--------')
    return hideLoading.apply(this, param); // 原样移交函数参数和this
  }
});
Object.defineProperty(wx, 'showToast', {
  configurable: true, // 是否可以配置
  enumerable: true, // 是否可迭代
  writable: true, // 是否可重写
  value(...param) {
    if (isShowLoading) { // Toast优先级更高
      wx.hideLoading();
    }
    isShowToast = true;
    console.error('--------showToast--------')
    return showToast.apply(this, param); // 原样移交函数参数和this
  }
});
Object.defineProperty(wx, 'hideToast', {
  configurable: true, // 是否可以配置
  enumerable: true, // 是否可迭代
  writable: true, // 是否可重写
  value(...param) {
    isShowToast = false;
    console.error('--------hideToast--------')
    return hideToast.apply(this, param); // 原样移交函数参数和this
  }
});

调整后展示逻辑为:

  1. 优先级:Toast>Loading,如果Toast正在显示,调用showLoading、hideLoading将无效
  2. 调用showToast时,如果Loading正在显示,则先调用 wx.hideLoading 隐藏Loading
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值