javascript - React.js。如何更改关键字 'this'

标签 javascript reactjs

我正在尝试从 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/

相关文章:

javascript - CORS ajax请求说明

javascript - 在 d3.js 中对 x 轴上的日期进行排序

php - HTML5 数据库连接丢失

javascript - react 选择可创建的 "no options"而不是 "create"

reactjs - Recharts 不适用于带有 typescript 的 React

javascript - 从通过 React Router 设置的路由访问 Redux Store

javascript - Next Div 左右浮动两个div后显示不正确

javascript - 为什么我的 React Context Helper 函数使用过时的状态?

css - 导航栏向左移动时超出页面内容的长度

javascript - 使用 ES6 中的 map 函数更新对象的属性值