「Krystalcsdn」的原创文章 微信小程序Cannot read property 'setData' of undefined问题解决 两种方法可用

微信小程序Cannot read property ‘setData‘ of undefined问题解决

Krystalcsdn 2020-03-08 23:57:39 300 收藏
展开
今天写小程序,需要读取窗口高度然后设置scroll-view高度,在this.setData时报错“Cannot read property ‘setData‘ of undefined”,代码如下:

onShow: function () {
wx.getSystemInfo({
success: function(res) {
this.setData({
scrollHeight:res.windowHeight-100*res.windowHeight/750
});
},
});
},
原因是getSystemInfo函数体中的this指向闭包,而不是page对象,所以需要在函数外定义this才能用。

onShow: function () {
var that = this;
wx.getSystemInfo({
success: function(res) {
that.setData({
scrollHeight:res.windowHeight-100*res.windowHeight/750
});
console.log(that.data.scrollHeight);
},
});
},
另外一种解决方法是使用箭头函数,ES6规定箭头函数没有自己的this,导致内部的this指向外层代码的this(最近的this),这个指向在定义时就已经确定,不会在执行时再指向执行环境的this。

「Krystalcsdn」的原创文章 微信小程序Cannot read property 'setData' of undefined问题解决 两种方法可用

因此可以:

onShow() {
wx.getSystemInfo({
success: (res) => {
//80为顶部搜索框区域高度 rpx转px 屏幕宽度/750
this.setData({
scrollHeight: res.windowHeight - (100 * res.windowWidth / 750)
});
}
})
},
普通函数this和箭头函数this对比分析详细见这篇文章https://segmentfault.com/a/1190000014027459

关于this的指向
总的来说:
this指向执行主体

分几种情况:
普通函数执行时,如果没有执行主体,在非严格模式下指向window,在严格模式下指向undefined。
箭头函数没有this,它继承上下文的this。
构造函数里的this指向生成的实例对象。
事件绑定函数中的this指向当前操作的元素。
call, apply, bind把函数中的this改为指定的执行对象。
————————————————
版权声明:本文为CSDN博主「Krystalcsdn」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/KrystalCSDN/article/details/104743327

相关文章