ウィジェット-非同期リクエストでthisを呼び出します.setData({})

7980 ワード

シナリオ:
pageのdataには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' });   //           
    	}
	})
}

上はこれsetDataのthisオブジェクトはもうpageではありません.thisが失われたため、リクエストの前にthat=thisを定義し、thatを使用する必要があります.setData({})のみ可能です.
注意、thatはグローバル変数として書くことはできません.必ずメソッドに書き、非同期リクエストの前に書きます.
方法1
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
    	}
	})
}

もう1つの方法は、ES 6の矢印関数であり、矢印関数には独自のthisはなく、そのthisは外を継承しているので、内部のthisは外層コードブロックのthisである.
方法2
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関数も受け入れます.