微信小程序Cannot read property 'setData' of undefined踩坑解决

本文探讨了微信小程序中两种不同的函数定义方式:function(e) {}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

微信小程序有函数有两种写法
比如我实现长按删除图片功能
wxml:

 <image class='addpic' src='{{item}}' data-index="comp_{{index}}" bindtap="previewImage" bindlongpress='deleteImg'></image>

第一种写法

  deleteImg: function(e){ //长按删除图片
    console.log("长按删除图片");
    var index = e.currentTarget.dataset.index;
    var id = index.split("_")[0];
    index = index.split("_")[1];
    console.log(index);
    console.log(id);
    var myThis= this
    //删除图片
    wx.showModal({
      title: '提示',
      content: '是否要删除图片?',
      showCancel: true,
      success: function (res) {
        console.log("删除图片")

        src_json["src_" + id].splice(index, 1);
        myThis.setData({
          src_comp: src_json["src_" + id]
        })
        
      }
    })
   
  }

第二种写法:

deleteImg:(e)=>{ //长按删除图片
    console.log("长按删除图片");
    var index = e.currentTarget.dataset.index;
    var id = index.split("_")[0];
    index = index.split("_")[1];
    console.log(index);
    console.log(id);
    var myThis= this
    //删除图片
    wx.showModal({
      title: '提示',
      content: '是否要删除图片?',
      showCancel: true,
      success: function (res) {
        console.log("删除图片")

        src_json["src_" + id].splice(index, 1);
        myThis.setData({
          src_comp: src_json["src_" + id]
        })
        
      }
    })
   
  }

发现没有,写法差距就在定义函数的时候,一个用是function(e){},另一个用的是(e)=>{}
两种区别居然是第一种有this可以调用,后一种没有this的
用(e)=>{}会报错
在这里插入图片描述
其实这里报错的原因应该是箭头函数体中的 this 对象,是定义函数时的对象,而不是使用函数时的对象。这是ES6标准新加的函数规则

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值