compressImage里setData无效
发布于 7 年前 作者 wuyang 2682 次浏览 来自 问答
wx.compressImage({
          src: res.tempImagePath, // 原图片路径
          quality: 50, // 压缩质量,
          complete: compRes => {
            console.log(compRes.tempFilePath)
            this.setData({
              'form.compImg': compRes.tempFilePath
            })
          }
        })

console.log(compRes.tempFilePath)能打印出来正确的临时路径,但是往form.compImg里赋值就是一直时undefined??

3 回复
onTakePhoto() {
    var that = this;
    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        wx.compressImage({
          src: res.tempImagePath, // 原图片路径
          quality: 50, // 压缩质量,
          complete: compRes => {
            console.log(compRes.tempFilePath)
            that.setData({
              'form.compImg': compRes.tempFilePath
            })
          }
        })
        that.setData({
          src: res.tempImagePath,
          'form.img': res.tempImagePath
        })
        console.log('compImg:', that.data.form.compImg)
        console.log('orignImg:', that.data.form.img)
      }
    })
  }

异步回调里面 setData 不能用this,在回调外把this赋给一个变量

that=this

//…

that.setData({

//…

我是拍照后,对图片进行压缩再上传的

onTakePhoto() {
    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        wx.compressImage({
          src: res.tempImagePath, // 原图片路径
          quality: 50, // 压缩质量,
          complete: compRes => {
            console.log(compRes.tempFilePath)
            this.setData({
              'form.compImg': compRes.tempFilePath
            })
          }
        })
        this.setData({
          src: res.tempImagePath,
          'form.img': res.tempImagePath
        })
        console.log('compImg:', this.data.form.compImg)
        console.log('orignImg:', this.data.form.img)
      }
    })
  }
回到顶部