我正在尝试从 Firebase 获取每个图像下载 URL。似乎第一个“这个”与第二个“这个”不同。如果我想让第二个'this'等于第一个'this'的值,我该怎么办?非常感谢!
getAllURL = product => {
// Get all the images from the firebase
var storage = firebase.storage();
console.log(this) // first this
const storageRef = storage.ref(`image/${product}`)
storageRef.listAll().then(function(result) {
result.items.forEach(function(imageRef) {
imageRef.getDownloadURL().then(function(url) {
console.log(this) // second this is undefined
}).catch(function(error) {});
})
})
}
componentDidMount() {
axios.get('/user/product')
.then(res=>{
if(res.data.code==0) {
this.setState({data:res.data.data},function(){
for (var i = 0; i < this.state.data.length; i++){
this.getAllURL(this.state.data[i].productName)
}
})
}
})
}
最佳答案
这个
是最confusing features在 JavaScript 中。我建议您更多地了解该主题。
至于快捷方式,有很多方法可以实现。
第一种方法:首先将第一个 this 分配给某个变量。
getAllURL = product => {
// Get all the images from the firebase
var storage = firebase.storage();
console.log(this) // first this
var firstThis = this; // some people prefered to assign "var that = this;", lol
const storageRef = storage.ref(`image/${product}`)
storageRef.listAll().then(function(result) {
result.items.forEach(function(imageRef) {
imageRef.getDownloadURL().then(function(url) {
console.log(firstThis); // use the new variable to refer to the firstThis
}).catch(function(error) {});
});
});
}
第二种方法:利用 javascript 中的 bind
函数(更高级一点,从函数式编程的 Angular 来看更容易接受)
getAllURL = product => {
// Get all the images from the firebase
var storage = firebase.storage();
console.log(this) // first this
const storageRef = storage.ref(`image/${product}`)
storageRef.listAll().then((function(result) {
result.items.forEach((function(imageRef) {
imageRef.getDownloadURL().then((function(url) {
console.log(this);
}).bind(this)).catch(function(error) {}); // yet another binding to propagate "this" inside
}).bind(this)); // another binding to force "this" on this yet another inline function to equal the first this (propagate it down)
}).bind(this)); // this binding will force "this" inside this inline function to equals the firstThis
}
注意:如果减少内联函数的数量,可能会减少困惑
getAllURL = product => {
// Get all the images from the firebase
var storage = firebase.storage();
console.log(this) // first this
const storageRef = storage.ref(`image/${product}`)
storageRef.listAll().then(listAllCallback.bind(this));
}
function listAllCallback(result) {
for (var i = 0; i<result.items.length; i++) {
var imageRef = result.items[i];
imageRef.getDownloadURL()
.then(downloadUrlCallback.bind(this))
.catch(function(error) {});
}
}
function downloadUrlCallback(url) {
console.log(this); // second this
}
关于javascript - React.js。如何更改关键字 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58828891/