Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.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
React native 外部作用域在js then函数中丢失_React Native_Ecmascript 6 - Fatal编程技术网

React native 外部作用域在js then函数中丢失

React native 外部作用域在js then函数中丢失,react-native,ecmascript-6,React Native,Ecmascript 6,我对母语和ES6不太熟悉。我可以访问此代码中的外部作用域“this”: my_function() { this.setState = {};//outer scope this return fetch('https://facebook.github.io/react-native/movies.json') .then((response) => { console.log(this); //this shows the correct

我对母语和ES6不太熟悉。我可以访问此代码中的外部作用域“this”:

my_function()
{
    this.setState = {};//outer scope this

    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => {
        console.log(this); //this shows the correct outer scope this
        return response.json()})
      .then(...);

}     
但如果我把这个箭头函数写为:

 return fetch('https://facebook.github.io/react-native/movies.json')
        .then(function(response){
           console.log(this); //this becomes some 'DedicatedWorkerGlobalScope' when I am debugging?
           return response.json();
        }).then(...)

我不明白为什么这两个函数不相等?

因为箭头函数是自动绑定的

如果你想得到同样的结果,你应该写:

return fetch('https://facebook.github.io/react-native/movies.json')
    .then(function(response){
       console.log(this); //this becomes some 'DedicatedWorkerGlobalScope' when I am debugging?
       return response.json();
    }.bind(this)).then(...)
我在函数的结束“}”之后添加了“.bind(this)”