请教setData()的用法
发布于 5 年前 作者 xia98 7179 次浏览 来自 问答

项目要求:

点击页面上的“拍照”按钮拍摄一张照片,然后将照片展示在页面上。

代      码:

<button bindtap=“chooseImage”>拍照</button>
<image src="{{src}}"></image>

Page({
  data: {
    src: “”
  },
  chooseImage: function () {
    wx.chooseImage({
      count: 1,
      sizeType: [‘original’, ‘compressed’],
      sourceType: [‘album’, ‘camera’],
      success: function (res) {
        var tempFilePath = res.tempFilePaths
        this.setData({
          src: tempFilePath[0]
        });
      }
    });
  }
});

问   题:

在开发工具中测试,点击“拍照”按钮,可以正常选择本机中的图片。

但图片选中后,<image>组件没有反应,并不展示选中的图片。查看开发工具的“调试”,显示:

WAService.js:3 thirdScriptError
this.setData is not a function;at pages/test1/test1 chooseImage function;at api chooseImage success callback function
TypeError: this.setData is not a function

………

求教!!!

7 回复

哪有书啊,就看微信官方的doc呗

………

sourceType: [‘album’, ‘camera’],
      success: function (res) {
        var tempFilePath = res.tempFilePaths;
        var that = this;
        that.setData({
          src: tempFilePath[0]
        });
      } 

………

依旧错误提示

WAService.js:3 thirdScriptError
that.setData is not a function;at pages/test1/test1 chooseImage function;at api chooseImage success callback function
TypeError: that.setData is not a function

多谢。问题解决。

初学小白,对this的了解极少。不情之请:就这个问题,能否推荐一下应该多看一下哪方面的书籍?

:)

谢了

 var that = this;放到function内第一行

在网络请求之前定义 var that =this;

在处理网络返回数据时,不能直接使用this。 要事先定义一个this的代理。

var that =this;

that.setData({

});

回到顶部