微信小程序之回调函数中用setData

起因: 想在某个回调函数中用setData 改变值

出错的代码:

 Page({
  data: {
    userinfo : 'notknow'
  },
  getuser1 : function(){
    console.log('hello');
    wx.getSystemInfo({
      success: function(res) {
        console.log(res)
        that.setData({
          userinfo: '???'
        })
      },
    })
  },

我们发现这样做了以后并不能在getsysteminfo里面改变userinfo的值,经过查阅资料以后,得知是因为success返回的是闭包
所以为了解决问题,我们在其中加入一行语句
const that = this;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userinfo : 'notknow'
  },

  getuser1 : function(){
    const that = this;
    
    console.log('hello');
    
    wx.getSystemInfo({
      success: function(res) {
        console.log(res)
        that.setData({
          userinfo: '???'
        })
      },
    })
  },
发布了59 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43914889/article/details/104185141
今日推荐