在寫小程序時,通常在回調函數時使用this.setData({});時編譯器會報this.setData is not a function的錯誤
因為this作用域指向問題 ,success函數實際是一個閉包 , 無法直接通過this來setData
解決方法有2個:
1 改造回調函數的方法為es6寫法:
success: function(res){
this.setData({});
},
改造為
success: (res)=>{
this.setData({});
},
即可。
因為當我們使用箭頭函數時,函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。
2 在函數開始時定義一個變量指向this
addImg:function(){
wx.chooseImage({
success: function(res){
var tempFilePaths= res.tempFilePaths;
this.setData({
picUrl: tempFilePaths[0],
temPath: tempFilePaths
});
},
});
}
改造為:
addImg:function(){
var _this = this;
wx.chooseImage({
success: function(res){
var tempFilePaths= res.tempFilePaths;
_this.setData({
picUrl: tempFilePaths[0],
temPath: tempFilePaths
});
},
});
}
即可。