避免使用额外的变量来存储es6中的引用

Ale*_*ong 2 javascript ecmascript-6 reactjs

我已经在使用react es6但仍然在这种情况下,我不知道如何避免使用它this:

const that = this;

UploadApi.exec(file).then(data => {
    that.setState({ loading : false});
});
Run Code Online (Sandbox Code Playgroud)

May*_*kla 6

在此示例中,您已在使用arrow function,因此reference不需要将其存储在单独的变量中.你可以直接使用这样的this关键字:

//const that = this;

UploadApi.exec(file).then(data => {
    this.setState({ loading : false});
});
Run Code Online (Sandbox Code Playgroud)

reference当你callback method像这样使用时,存储在一个单独的变量中:

const that = this;

UploadApi.exec(file).then(function(data){
    that.setState({ loading : false});
});
Run Code Online (Sandbox Code Playgroud)

但是,你可以通过使用.bind(this)with 来避免额外的变量callback method,如下所示:

//const that = this;

UploadApi.exec(file).then(function(data){
    this.setState({ loading : false});
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

检查此答案以获取完整的详细信息,箭头功能与功能声明