【JS】Cannot read property 'setData' of undefined & 关于this问题

【JS】Cannot read property 'setData' of undefined & 关于this问题

参考

  • 常出现不能使用this.函数的问题,考虑是不是 this指代对象 发生错误的问题。

  • 解决1:常使用var that=this;保存当前this对象,在后面进行使用

    getUserProfile(e) {
        var that = this;
        wx.getUserProfile({
          success(res) {
            that.setData({
              userInfo: res.userInfo
            })
          }
        })
    }
    
  • 解决2:使用ES6的箭头函数

    getUserProfile(e) {
        wx.getUserProfile({
          success:(res)=>{
            this.setData({
              userInfo: res.userInfo
            })
          }
        })
    }
    
posted @ 2021-04-08 17:36  musecho  阅读(156)  评论(0编辑  收藏  举报