使用 this.setData赋值失败?

发布于 6 年前作者 min061869 次浏览最后编辑 6 年前来自 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 回复
changna
changna1 楼6 年前
console.log("用户卡片高度"+that.data.userInfoCardHeight)这一句放在方法体里面
laiming
laiming2 楼6 年前
同步异步问题,setData是异步的。像你那样写setData还没赋值完就先执行了打印,肯定是空的咯。改为这样。
that.setData({
   userInfoCardHeight:res.windowHeight-qRes.height
}, ()=> {
  console.log(that.data.userInfoCardHeight)
})
qiangwan
qiangwan3 楼6 年前

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

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

sliang
sliang4 楼4 年前

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