使用 this.setData赋值失败?
发布于 5 年前 作者 min06 1657 次浏览 来自 官方Issues
onReady: function () {
    let that = this
    wx.getSystemInfo({
      complete: (res) => {
        var query = wx.createSelectorQuery()
        query.select('#bottom').boundingClientRect(function(qRes) {
          that.setData({
            userInfoCardHeight:res.windowHeight-qRes.height
          })
          console.log(res.windowHeight-qRes.height)
        }).exec();
      },
    })
    console.log("用户卡片高度"+that.data.userInfoCardHeight)
  },
4 回复
console.log("用户卡片高度"+that.data.userInfoCardHeight)这一句放在方法体里面
同步异步问题,setData是异步的。像你那样写setData还没赋值完就先执行了打印,肯定是空的咯。改为这样。
that.setData({
   userInfoCardHeight:res.windowHeight-qRes.height
}, ()=> {
  console.log(that.data.userInfoCardHeight)
})

setData函数用于将数据从逻辑层发送到视图层(异步),同时改变对应的this.data的值(同步)。

https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html#Page.prototype.setData(Object%20data,%20Function%20callback)

不是赋值失败,是异步执行的问题,看一下控制台的打印顺序就知道了

回到顶部