场景:在函数内使用了一个网络请求,返回的信息通过setData更新到页面
sendClick: function(e) {
// 将新发的消息添加到数组列表中
msgList.push({
speaker: 'customer',
contentType: 'text',
content: 'hello,world'
})
// 在此处可以直接通过this访问
this.setData({
msgList,
});
// 发送网络请求
wx.request({
method: "POST",
url: "",
data: {
'speaker': 'customer',
'contentType': 'text',
'content': 'hello,world'
},
success:function(res){
// 获取接收到的信息,然后添加到msgList数组中
msgList.push({
speaker: res.data['speaker'],
contentType: res.data['contentType'],
content: res.data['content']
})
// 更新到页面中
this.setData({#这里报错
msgList,
});
},
})
},
报错:
Cannot read property ‘setData’ of null;at pages/message/message
onReady function;at api request success callback function TypeError:
Cannot read property ‘setData’ of null
解决:
因为success是闭包,所以在这里使用的this指向的是闭包里面的,自然使用不了setData。解决办法就是在请求外面设置一个临时变量
sendClick: function(e) {
// 将新发的消息添加到数组列表中
msgList.push({
speaker: 'customer',
contentType: 'text',
content: 'hello,world'
})
// 在此处可以直接通过this访问
this.setData({
msgList,
});
//将this对象复制到临时变量that
var that = this;
// 发送网络请求
wx.request({
method: "POST",
url: "",
data: {
'speaker': 'customer',
'contentType': 'text',
'content': 'hello,world'
},
success:function(res){
// 获取接收到的信息,然后添加到msgList数组中
msgList.push({
speaker: res.data['speaker'],
contentType: res.data['contentType'],
content: res.data['content']
})
// 此时that指向的就是上一层的this对象
that.setData({
msgList,
});
},
})
},