背景:用 wx.request 請(qǐng)求到數(shù)據(jù)后,想 this.setData 來改變某個(gè)按鈕的內(nèi)容兵迅。發(fā)現(xiàn) this.setData 會(huì)報(bào)錯(cuò)「Cannot read property 'setData' of null」
示例一:為錯(cuò)誤示例 泰讽,會(huì)出現(xiàn) this.setData is not a function 的報(bào)錯(cuò)例衍,原因是此時(shí)的this對(duì)象指的是setTimeout 里面的匿名函數(shù)對(duì)象 , 但是在這種情況下還是想動(dòng)態(tài)渲染視圖已卸,就需要把當(dāng)前的this的狀態(tài)保存起來佛玄,然后在 setTimeout 里面的匿名函數(shù)對(duì)象內(nèi)調(diào)用。如示例二
片段1
onLoad:function(){
setTimeout(function () {
this.setData({
open: 111
},1000)
})
},
示例二:保存當(dāng)前對(duì)象的this狀態(tài)咬最,在 setTimeout 里面的匿名函數(shù)對(duì)象內(nèi)調(diào)用 翎嫡, 此時(shí)能夠做到動(dòng)態(tài)選擇視圖同時(shí)數(shù)據(jù)和視圖都不會(huì)出錯(cuò)
片段2
onLoad:function(){
var that= this;
setTimeout(function () {
that.setData({
open: 111
},1000)
})
},
參考
https://blog.csdn.net/qq_35713752/article/details/78879984