在 axios get forEach 中调用方法

Calling a method within an axios get forEach

我正在尝试调用 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

^上面明明可以得到所有的item,为什么调用这些item的方法却得到undefined?

下面的代码有效(它得到了正确的点赞)。当用户按赞时我会使用它,但是我还需要首先获得所有的赞,这就是我在上面尝试做的。

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);
    })

因为ES6arrow functions不绑定自己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 使用箭头函数,因为它将 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);
    });
  })