项目场景
onLoad: function (options) {
wx.request({
url: 'https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata',
success: function(res){
// success
this.setData({
swiperList: res.data.message
})
}
})
}
问题描述
TypeError: Cannot read property 'setData' of undefined
使用 ES6 箭头函数(箭头函数 this
为父作用域的 this
,不是调用时的 this
)
onLoad: function (options) {
wx.request({
url: 'https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata',
success: (res) => {
// success
this.setData({
swiperList: res.data.message
})
}
})
}
方案二
- 添加
var that = this;
- 把
sucess
中的this.setData
改成that.setData
onLoad: function (options) {
var that = this;
wx.request({
url: 'https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata',
success: function (res) {
// success
that.setData({
swiperList: res.data.message
})
}
})
}
引用参考
- https://blog.csdn.net/weixin_46419373/article/details/107823779
- https://blog.csdn.net/qq_43263320/article/details/113706520
- https://www.cnblogs.com/mengff/p/9656486.html