Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 避免使用额外变量在es6中存储引用_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript 避免使用额外变量在es6中存储引用

Javascript 避免使用额外变量在es6中存储引用,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我已经在使用react es6,但在这种情况下,我不知道如何避免将其用于此: const that = this; UploadApi.exec(file).then(data => { that.setState({ loading : false}); }); 在本例中,您已经在使用箭头函数,因此不需要将引用存储在单独的变量中。您可以像这样直接使用这个关键字: //const that = this; UploadApi.exec(file).then(data =>

我已经在使用
react es6
,但在这种情况下,我不知道如何避免将其用于

const that = this;

UploadApi.exec(file).then(data => {
    that.setState({ loading : false});
});

在本例中,您已经在使用
箭头函数
,因此不需要将
引用
存储在单独的变量中。您可以像这样直接使用
这个
关键字:

//const that = this;

UploadApi.exec(file).then(data => {
    this.setState({ loading : false});
});
const that = this;

UploadApi.exec(file).then(function(data){
    that.setState({ loading : false});
});
//const that = this;

UploadApi.exec(file).then(function(data){
    this.setState({ loading : false});
}.bind(this));
使用
回调方法时,需要将
引用
存储在单独的变量中,如下所示:

//const that = this;

UploadApi.exec(file).then(data => {
    this.setState({ loading : false});
});
const that = this;

UploadApi.exec(file).then(function(data){
    that.setState({ loading : false});
});
//const that = this;

UploadApi.exec(file).then(function(data){
    this.setState({ loading : false});
}.bind(this));
但是,您可以使用
.bind(this)
回调方法来避免额外的变量,如下所示:

//const that = this;

UploadApi.exec(file).then(data => {
    this.setState({ loading : false});
});
const that = this;

UploadApi.exec(file).then(function(data){
    that.setState({ loading : false});
});
//const that = this;

UploadApi.exec(file).then(function(data){
    this.setState({ loading : false});
}.bind(this));

请检查此答案以了解完整的详细信息,

您需要以这种方式创建yout UploadApi.exec,以便在传输javascript后相应地创建它。如下所示

UploadApi.exec(file).then(data => {
    this.setState({ loading : false});
});
在您上传的API中

exec=(file:any):Q.Promise=>{

}
然后像下面那样使用它

UploadApi.exec(file).then(data => {
    this.setState({ loading : false});
});

(数据)=>{this}不起作用?在本例中,您可以直接在当前有
that
的地方使用
this