微信小程序的this和that的用法
2022-06-21 本文已影响0人
_静夜听雨_
在微信小程序中,我们经常会使用this.setData来修改数据,但有时候发现,this拿不到,到底是为什么呢?
bindHandle: function () {
this.setData({
index: 22
})
}
场景
当我们通过wx.request请求网络数据成功后绑定数据时候报以下错误
this.setData is not a function
queryDataList:function(){
wx.request({
url: url,
method:'POST',
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
if (res.data.code == 0){
this.setData({
dataList: res.data.dataList
});
}
}
})
}
这是因为this作用域指向问题 ,success函数实际是一个闭包 , 无法直接通过this来setData
如何解决呢?
方法一:保留this的副本that
queryDataList:function(){
var that = this
wx.request({
url: url,
method:'POST',
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
if (res.data.code == 0){
that.setData({
dataList: res.data.dataList
});
}
}
})
}
方法二:回调函数使用函数声明(箭头函数)的写法
queryDataList:function(){
wx.request({
url: url,
method:'POST',
header: {
'content-type': 'application/json' // 默认值
},
success: (res) => {
if (res.data.code == 0){
this.setData({
dataList: res.data.dataList
});
}
}
})
}
总结
从上面情景中我们发现,问题主要出现在调用接口的回调函数中,所以我们在success或者fail回调函数中要setData的时候,就要选择其中一种方式来避免this丢失