微信小程序报错:TypeError: Cannot read property ‘substring‘ of undefined

  • Post author:
  • Post category:小程序



具体报错截图:


报错的关键代码:

<wxs src="../../../utils/business.wxs" module="business" />

<view class="order-item-content">{{business.fomatTime(item.checkBillTime)}} </view>

提示报错是上面的关键代码,但微信小程序前端已经能打印后端发送过来的数据,问题应该是 在使用该函数时,传入了空的值 以导致数据渲染报错。


已打印调用函数前后格式对比:

调用前格式:20200809152640

调用后格式: 2020-08-09 15:26:40


调用函数business.wxs

var fomatTime = function(time){
  return time.substring(0, 4) + "-" + time.substring(4, 6) + "-" + time.substring(6, 8) + " " + time.substring(8, 10) + ":" +
  time.substring(10, 12) + ":" + time.substring(12, 14);
}

module.exports = {
  fomatTime:fomatTime
}

处理思路:利用三元表达式处理所取字符串为空的情况即可

<view class="order-item-content">
{{item.checkBillTime ? business.fomatTime(item.checkBillTime) : ""}}
</view>

再优化wxs代码,处理值为空的情况,以防出现值为空返回”–::”的数据 ;处理例如 :


” ”



这种数据(trim是js中处理字符串空格问题的)

var fomatTime = function(time){
    if(time.trim()){
      return time.substring(0, 4) + "-" + time.substring(4, 6) + "-" + time.substring(6, 8) + " " + time.substring(8, 10) + ":" +
    time.substring(10, 12) + ":" + time.substring(12, 14);
    }
    else{
      return "";
    }
}


处理完毕之后没有报错发生;


PS:此为个人学习笔记报错处理,若看完毫无帮助,实在抱歉;



版权声明:本文为unstoppableyi原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。