foreword
Recently, when developing WeChat applets, I have encountered a very strange problem from time to time. In some cases, using
this.setData
can change the view display, and in some cases, usingthis.setData
is invalid. Why is this?
Problem Description
Before explaining this problem, let's look at two pieces of code:
The first piece of code (wrong wording)
initOn() {
wx.request({
url: "接口地址",
success: function (res) {
this.setData({
objs: res.data.map.gdtzxx,
});
},
});
},
The second piece of code (correct writing)
initOn() {
let that = this;
wx.request({
url: "接口地址",
success: function (res) {
that.setData({
objs: res.data.map.gdtzxx,
});
},
});
},
By comparing the above codes, we found that the only difference between the two is in this
the use of , the first is to use directly this
to call, and the other is to let that = this
use that
to save the current this
state of the to update the view. Although it seems that the ultimate purpose is the same, when you run it, the first way of writing will report an error as shown in the figure below:
Cause Analysis
This is because of the problem pointed to by this
the scope , success
the function is actually a closure, and cannot be this
passed setData
, so an error will be reported.
But es6
in , this problem does not exist when using arrow functions. The reason is because when we use an arrow function, this
the object is the object where it is defined, not the object where it is used. It is not because there is a this
binding , the actual reason is that the arrow function does not have its own at all this
, its this
is inherited from the outside, so the internal this
is the outer code block this
.
es6
Arrow function writing
initOn() {
wx.request({
url: "接口地址",
success: (res) => {
this.setData({
objs: res.data.map.gdtzxx,
});
},
});
},