微信小程序中使用箭头函数导致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指向不明