【问题标题】:ES6 ReactJS class and this scope from callback [duplicate]ES6 ReactJS 类和回调中的这个范围 [重复]
【发布时间】:2016-03-01 13:57:29
【问题描述】:

我在 StackOverflow 上搜索了 StackOverflow 的这个问题,但还没有找到答案,如果已经得到答案,请耐心等待。

我在 ES6 中定义一个类(使用 ReactJS,尽管这与问题有些无关)如下。我想从我的 fetch 回调中修改 this.size 和 this._cache,但是我似乎无法直接操作“this”,因为它显然引用了类实例化之外的另一个对象。在定义要绑定到 this 的 var 时,它确实可以引用对象,但我觉得这不是 ES6 最好的方法:

class MyDataListStore {

    constructor(url) {
        this.url = url;
        this.size = 0;
        this._cache = [];
        this.getRemoteData();
    }

    getRemoteData() {
        var that = this;
        fetch(this.url).then(function(response) {
             return response.json();
        }).then(function(j) {
             that.size = j["total"];
             that._cache = j["table"];
    });
    }
}

我觉得我在 ES6 中遗漏了一些东西,可能有更好的方法来做到这一点。

谢谢!

【问题讨论】:

  • 对不起,我实际上是在构造函数的底部调用它,忘记添加行,现在编辑。

标签: javascript reactjs scope ecmascript-6


【解决方案1】:

应该这样做:

getRemoteData() {
  fetch(this.url)
  .then((response) => response.json())
  .then((j) => {
     this.size = j.total;
     this._cache = j.table;
  });
}

【讨论】:

  • 这对范围有什么影响?在我最初的示例中,“this”绑定到回调,但在这个中,它绑定到类对象?
  • @Loic Duros github.com/lukehoban/es6features#arrows - 请先阅读本文
猜你喜欢
  • 1970-01-01
  • 2016-07-11
  • 2010-09-16
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 2016-07-29
  • 1970-01-01
  • 2016-11-30
相关资源
最近更新 更多