React.js。如何更改关键字“ this”

问题描述 投票:0回答:1

我正在尝试从Firebase获取每个图像的下载URL。似乎第一个'this'第二个'this'不同。如果我想让第二个'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)  
                    }                     
                 })
            }
        })
 }  

我正在尝试从Firebase获取每个图像的下载URL。似乎第一个“ this”与第二个不同。如果我想让第二个'this'等于第一个的值,什么...

javascript reactjs
1个回答
0
投票

当您使用function而不是箭头功能时,它会重新绑定this,从而导致您遇到的情况。

© www.soinside.com 2019 - 2024. All rights reserved.