Javascript React.js。如何更改关键字“this”
我正在尝试从Firebase获取每个图像下载URL。第一个“这”似乎与第二个不同。如果我想让第二个‘this’等于第一个的值,我应该怎么做?非常感谢你Javascript React.js。如何更改关键字“this”,javascript,reactjs,Javascript,Reactjs,我正在尝试从Firebase获取每个图像下载URL。第一个“这”似乎与第二个不同。如果我想让第二个‘this’等于第一个的值,我应该怎么做?非常感谢你 getAllURL = product => { // Get all the images from the firebase var storage = firebase.storage(); console.log(this) // first this const storageRef = s
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)
}
})
}
})
}
这是Javascript中最流行的一种。我建议你多看看这个话题
至于捷径,有很多方法可以解决
第一种方法:只需先将第一个变量赋给某个变量
getAllURL=产品=>{
//从firebase获取所有图像
var存储=firebase.storage;
console.logthis//
var firstThis=this;//有些人更喜欢分配var that=this;,lol
const storageRef=storage.ref`image/${product}`
storageRef.listAll.thenfunctionresult{
result.items.forEachfunctionimageRef{
imageRef.getDownloadURL.thenfunctionurl{
console.logfirstThis;//使用新变量引用firstThis
}.catchfunctionerror{};
};
};
}
第二种方法:在javascript中使用bind函数更高级一些,从函数编程的角度来看效果更好
getAllURL=产品=>{
//从firebase获取所有图像
var存储=firebase.storage;
console.logthis//
const storageRef=storage.ref`image/${product}`
storageRef.listAll.thenfunctionresult{
result.items.forEachfunctionimageRef{
imageRef.getDownloadURL.thenfunctionurl{
console.logthis;
}.bindthis.catchfunctionerror{};//另一个要在内部传播此内容的绑定
}.bindthis;//另一个绑定强制此函数,另一个内联函数等于此函数向下传播的第一个内联函数
}.bindthis;//此绑定将强制此内联函数中的this等于firstThis
}
注意:如果内联函数的数量减少,它可能会变得不那么混乱
getAllURL=产品=>{
//从firebase获取所有图像
var存储=firebase.storage;
console.logthis//
const storageRef=storage.ref`image/${product}`
storageRef.listAll.thenlistAllCallback.bindthis;
}
函数listAllCallbackresult{
对于var i=0;i,将常规函数更改为箭头函数。如果您想解释为什么这样做,快速谷歌搜索应该会得到结果。