微信小程序中使用箭头函数导致this指向错误的问题

微信小程序中使用箭头函数导致this指向错误的问题

今天开开心心地使用微信小程序,没想到在this.setData时候报错,如下:
代码

 onShow:()=>{
    console.log(this);
    this.setData({
      lists: [{
        name: "1221",
        age: 11,
        score: 33
      }]
    })
    db.collection("test").get({
      success:function(res){
        // console.log(that);
        // that.setData({
        //   lists: [{
        //     name: "1221",
        //     age: 11,
        //     score: 33
        //   }]
        // })
      }
    });
  }

报错如下:

VM1252:1 thirdScriptError
Cannot read property 'setData' of undefined;at "pages/index/index" page lifeCycleMethod onShow function
TypeError: Cannot read property 'setData' of undefined
    at G.onShow (http://127.0.0.1:19052/appservice/pages/index/index.js:17:14)
    at G.<anonymous> (http://127.0.0.1:19052/appservice/__dev__/WAService.js:1:838469)
    at G.p.__callPageLifeTime__ (http://127.0.0.1:19052/appservice/__dev__/WAService.js:1:838247)
    at Vt (http://127.0.0.1:19052/appservice/__dev__/WAService.js:1:853477)
    at Gt (http://127.0.0.1:19052/appservice/__dev__/WAService.js:1:854469)
    at zt (http://127.0.0.1:19052/appservice/__dev__/WAService.js:1:855762)
    at Function.<anonymous> (http://127.0.0.1:19052/appservice/__dev__/WAService.js:1:856872)
    at Bt.<anonymous> (http://127.0.0.1:19052/appservice/__dev__/WAService.js:1:821975)
    at Bt.emit (http://127.0.0.1:19052/appservice/__dev__/WAService.js:1:305615)
    at Object.emit (http://127.0.0.1:19052/appservice/__dev__/WAService.js:1:324480)

发现this变量为undefined;
最后发现是因为使用了箭头函数导致this指向的原因,使用微信的api时候不要使用箭头函数,可能会导致里面的this指向不明

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值