Wechat applet this points to the problem

foreword

Recently, when developing WeChat applets, I have encountered a very strange problem from time to time. In some cases, using this.setDatacan change the view display, and in some cases, using this.setDatais 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 thisthe use of , the first is to use directly thisto call, and the other is to let that = thisuse thatto save the current thisstate 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:

insert image description here


Cause Analysis

This is because of the problem pointed to by thisthe scope , successthe function is actually a closure, and cannot be thispassed setData, so an error will be reported.

But es6in , this problem does not exist when using arrow functions. The reason is because when we use an arrow function, thisthe object is the object where it is defined, not the object where it is used. It is not because there is a thisbinding , the actual reason is that the arrow function does not have its own at all this, its thisis inherited from the outside, so the internal thisis the outer code block this.

es6Arrow function writing

initOn() {
    
    
  wx.request({
    
    
    url: "接口地址",
    success: (res) => {
    
    
      this.setData({
    
    
        objs: res.data.map.gdtzxx,
      });
    },
  });
},

Guess you like

Origin blog.csdn.net/Shids_/article/details/129375122
Recommended