gpt4 book ai didi

javascript - 调用 axios get forEach 中的方法

转载 作者:行者123 更新时间:2023-11-28 12:16:44 24 4
gpt4 key购买 nike

我正在尝试调用GetLikes(item.id)方法位于 forEach 中在我的axios.get内功能。我收到一条错误,指出 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 arrow functions不绑定(bind)自己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);
});
})

不会绑定(bind)thisforEach循环(注意箭头函数)

关于javascript - 调用 axios get forEach 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47814903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com