React native 外部作用域在js then函数中丢失
我对母语和ES6不太熟悉。我可以访问此代码中的外部作用域“this”: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
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)”