小程序——异步请求中调用this.setData({})

情景:

page的data里有一个message,想要在执行wx.request成功的时候修改它的值。

data: {
	message:"hi~"
}

一般很容易这样写:

getMassage: function () {
	wx.request({
    	url: 'http://127.0.0.1/test.php',
    	method:'GET',
    	header: {
        	'content-type': 'application/json' 
    	},
    	success: function (res) {
        	console.log(res.data);
        	this.setData({ message: 'success' });   //错误的写法      
    	}
	})
}

上面 this.setData中的this对象已经不是page了。因为this丢失,需要在请求之前定义that = this, 使用that.setData({}) 才可以。

注意,that不能写成全局变量,一定要写在方法里,并且是异步请求之前。

方法一

getMassage: function () {
	let that = this      // 把当前的Page对象保存在that中
	wx.request({
    	url: 'http://127.0.0.1/test.php',
    	method:'GET',
    	header: {
        	'content-type': 'application/json' 
    	},
    	success: function (res) {
        	console.log(res.data);
        	that.setData({ message: 'success' });   //这里用that
    	}
	})
}

还有一个方法,就是ES6中的箭头函数,箭头函数没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。

方法二

getMassage: function () {
	let that = this      // 把当前的Page对象保存在that中
	wx.request({
    	url: 'http://127.0.0.1/test.php',
    	method:'GET',
    	header: {
        	'content-type': 'application/json' 
    	},
    	success:  (res) => {
        	console.log(res.data);
        	this.setData({ message: 'success' });   // 这里用this
    	}
	})
}

官方文档:https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html
小程序——异步请求中调用this.setData({})_第1张图片
this.setData()还接受一个callback函数,在数据从逻辑层发送到视图层之后调用。

你可能感兴趣的:(小程序)