微信小程序Cannot read property 'setData' of null错误

今天练习使用微信小程序chooseImage的API时遇到了这个小错误,一方面是粗心,一方面也是知识不牢固才犯错。

说到底,是不清楚数据的作用域,去访问了访问不到的数据。

背景:我想通过chooseImage这个API从本地读取一张图片(新数据),然后替换掉之前显示的图片(老数据),从而将读取的图片显示出来。其实也就是更改数据,如图:

通过日志信息可以知道,读取图片是没问题的。

但是将这个地址赋值给image标签的src时,却一直报错。

错误的代码段:

//index.js
Page({
  data: {
    userimage: "/images/cat.png", //默认的数据!!!!!!!!!!!!!
  },
  bindViewTap: function() {
    //利用API从本地读取一张图片
    wx.chooseImage({
      count: 1, 
      sizeType: ['original', 'compressed'], 
      sourceType: ['album', 'camera'], 
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        //将读取的图片替换之前的图片
        this.setData({userimage: tempFilePaths[0]}) //修改数据!!!!!!!!!!!!!
      }
    })
  }
})

正确的代码:

//index.js
Page({
  data: {
    userimage: "/images/cat.png",
  },
  bindViewTap: function() {
    var that=this //!!!!!!!!!“搭桥”

    //利用API从本地读取一张图片
    wx.chooseImage({
      count: 1, 
      sizeType: ['original', 'compressed'], 
      sourceType: ['album', 'camera'], 
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        //将读取的图片替换之前的图片
        that.setData({userimage: tempFilePaths[0]})//!!!!!通过that访问
      }
    })
  }
})

总结:

我想在wx.chooseImage()里面更改离它辣么遥远的userimage的值,使用this,访问不到userImage,所以要在bindViewTap(中间层),加上var that=this,作为桥梁,在wx.chooseImage里面才能通过桥梁that访问到userimage!

猜你喜欢

转载自blog.csdn.net/qq_42183184/article/details/82356208
今日推荐