我正在尝试调用forEach
和我的axios.get
函数中的GetLikes(item.id)
方法。我回到了一个错误,说明TypeError: Cannot read property 'GetLikes' of undefined
。
如果我评论了方法,我可以看到我能够获取所有项目及其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
输出以this.getLikes(item.ID)注释:
found: {…}
found id: 2
found: {…}
found id: 1
^上面显然可以获取所有项目,因此,如果我尝试在这些项目上调用方法,为什么要获得不确定?
以下代码有效(它具有正确的喜欢)。当用户按下这样的用户时,我也会使用它,但是我也需要最初获得所有喜欢的东西,这就是我要在上面尝试做的。
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
创建一个新的范围,因此您可以获得property 'GetLikes' of undefined
的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);
});
})