寫wx.request函數的sucess返回時,需要更改data里面的屬性值,this.setData遇到了undefined報錯
方法一:設置一個傳值變量that
1 onLoad: function (options) { 2 var that=this; //在此時this指的是window,把其賦給that 3 wx.request({ 4 url: '某地址', 5 method:"get", 6 data: { 7 msg: { 8 "buyerIdCard": "某證", 9 "status":"yes" 10 } 11 }, 12 header: { 13 "Content-Type": "application/json;charset=UTF-8" 14 }, 15 success:function(res){ 16 that.setData({ //在此就可直接用data中的屬性了 17 listArr:res.data.msg 18 }) 19 } 20 }) 21 },
原因:回調函數success中的this顯示undefined,需要將外層this傳進來。至於為啥會報undefined,有人給出解釋是this指向回調函數本身。挖個坑
方法二:使用箭頭函數:
success:(res)=>{ console.log(this); console.log(that); this.setData({ listArr:res.data.msg }) }
控制台顯示這兩個指向相同
原因:箭頭函數中this指向外層作用域,例子:
var obj = { foo() { console.log(this); }, bar: () => { console.log(this); } } obj.foo() // {foo: ƒ, bar: ƒ} obj.bar() // window