Cannot read property 'data' of undefined —— 小程序开发

  由于疫情原因目前处于半下岗状态,在家的时候就研究起了小程序开发。由于是新手,所以总会遇到各种问题,顺便记录一下。

wx.showModal({
  title: '提示',
  content: '这是一个模态弹窗',
  success (res) {
    if (res.confirm) {
      this.data.messageId
    } else if (res.cancel) {
      console.log('用户点击取消')
    }
  }
})

  如果这么写,会遇到“Cannot read property 'data' of undefined ”的错误。

  如果改成箭头函数的写法,就不会出错。

wx.showModal({
  title: '提示',
  content: '这是一个模态弹窗',
  success :(res)=> {
    if (res.confirm) {
      this.data.messageId
    } else if (res.cancel) {
      console.log('用户点击取消')
    }
  }
})

  分析原因,箭头函数是ES6的写法,不同的写法,会导致“this”的指代层级不同,所以会找不到data属性。

猜你喜欢

转载自www.cnblogs.com/iverson-3/p/12821454.html
今日推荐