Javascript 在axios get forEach中调用方法
我试图调用Javascript 在axios get forEach中调用方法,javascript,vue.js,axios,Javascript,Vue.js,Axios,我试图调用GetLikes(item.id)方法,该方法位于forEach中,并且在我的axios.get函数中。我返回一个错误,说明TypeError:无法读取未定义的属性“GetLikes” 如果我对该方法进行注释,我可以看到我能够获得所有项目及其ID,但是当我取消注释该方法时,它就不再工作了 axios .get("/api/endpoint") .then(response => { this.data = response.data; this.data.
GetLikes(item.id)
方法,该方法位于forEach
中,并且在我的axios.get
函数中。我返回一个错误,说明TypeError:无法读取未定义的属性“GetLikes”
如果我对该方法进行注释,我可以看到我能够获得所有项目及其ID,但是当我取消注释该方法时,它就不再工作了
axios
.get("/api/endpoint")
.then(response => {
this.data = response.data;
this.data.forEach(function(item) {
console.log("found: ", item)
console.log("found id: ", item.id)
this.GetLikes(item.id);
});
})
以上代码的输出:
由于某种原因,它似乎无法获取id 1,尽管相同的代码仅在没有以下方法的情况下获取id 1
found: {…}
found id: 2
TypeError: Cannot read property 'GetLikes' of undefined
注释掉此.GetLikes(item.id)的输出:
found: {…}
found id: 2
found: {…}
found id: 1
上面的^显然可以获取所有项目,那么,如果我尝试对这些项目调用方法,为什么会获取未定义的项目?
下面的代码有效(它得到了正确的结果)。当用户按下like时,我会使用它,但是我也需要首先得到所有的like,这就是我在上面尝试做的
Like(id) {
axios
.post("/like/" + id)
.then(response => {
this.GetLikes(id);
})
}
我错过了什么
this.data.forEach(function(item) {
console.log("found: ", item)
console.log("found id: ", item.id)
this.GetLikes(item.id);
});
上面的代码为this
创建了一个新的作用域,因此对于forEach
你不会有这个问题的
axios
.post("/like/" + id)
.then(response => {
this.GetLikes(id);
})
因为ES6不绑定自己的this
你可以试试看
axios
.get("/api/endpoint")
.then(response => {
this.data = response.data;
this.data.forEach((item) => {
console.log("found: ", item)
console.log("found id: ", item.id)
this.GetLikes(item.id);
});
})
它不会在
forEach
循环中绑定this
(注意箭头函数)对forEach
使用箭头函数,因为它将此绑定到包含范围
axios
.get("/api/endpoint")
.then(response => {
this.data = response.data;
this.data.forEach((item) => {
console.log("found: ", item)
console.log("found id: ", item.id)
this.GetLikes(item.id);
});
})
也许
this.GetLikes
中的this
并不是指您认为它在使用forEach(函数(项){
@AndrewLohr时的作用域。我该如何调试它?我为您的相关MDN文档写了一个关于箭头函数的答案。请参阅“无单独”部分“.谢谢,我在你评论谢谢你的时候编辑了它@AndrewLohr。我用另一种方法也遇到了同样的问题,似乎我已经完全忘记了过去的错误!@AndrewLohr np,你回答的对:)