關鍵是 let that = this
因為在onLoad 的 wx.request方法里, this指的是 wx.request 的上下文, 所以應該是在 onLoad 的時候定義 let that = this
調用遠程服務,序列化后,把obj賦值給bookList
最開始的報錯代碼如下:
Page({ data: { bookList: [] }, onLoad: function() { wx.request({ url: 'https://jiashubing.cn/wechat/book', header: { 'content-type': 'application/json' }, success(res) { var obj = JSON.parse(res.data) console.log(obj) this.setData({ bookList: obj }) } }) }})
報錯為:
VM3293:1 thirdScriptErrorCannot read property 'setData' of null;at pages/index/index onLoad function;at api request success callback functionTypeError: Cannot read property 'setData' of null
報錯原因是this 指向有問題,得在onload的時保存實例指向,let that = this,下面全用that,this指向永遠值得是自己的上下文環境
正確代碼如下:
Page({ data: { bookList: [] }, onLoad: function() { let that = this wx.request({ url: 'https://jiashubing.cn/wechat/book', header: { 'content-type': 'application/json' }, success(res) { var obj = JSON.parse(res.data) console.log(obj) that.setData({ bookList: obj }) } }) }})
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持IIS7站長之家。
新聞熱點
疑難解答