2017-04-13 116 views
3

在这个简单的例子中,我有一个带有密码字段的还原形式,试图用随机数字更新密码字段。如何将'this'与结果绑定?将'this'传递给axios promise'then'?

axios.get('https://www.random.org/integers/?num=1&min=1&max=20&col=1&base=10&format=plain&rnd=new').then(function(result) { 
     this.props.change('password', result.data); 
    }).catch(function(error) { 
      this.props.change('password', '999'); 
     }); 

我知道上面的逻辑工作正常,因为如果我使用ES5 var this1 = this;并使用this1它工作正常。

问候!

回答

2

要么你可以使用你刚才所描述的方法,即

var $this = this 
var func = function() { 
    $this.props.doSomething() 
} 

或者,你可以bind的功能与正确的this上下文中执行。在香草JS,你可以通过使用bind做到这一点:

var func = function() { 
    this.props.doSomething() 
} 
// now this inside func will always be whatever it was here 
func = func.bind(this) 

在ES6结合this匿名函数已经简化了arrow functions

const func =() => { 
    // this will be always whatever it was where this func was defined 
    this.props.doSomething() 
} 

希望这有助于!

+0

我做了一个改变,并使用ES6胖箭头功能,但它不能访问'this'。我甚至尝试过传递它。 [注意:现在使用promise.all] const func =()=> {Promise.all([axios.get('https://www.random.org/integers/?num=1&min=1&max=20&col=1&base ='&format = plain&rnd = new')]) .then(function(result){ console.log('promise fullfilled result.data =',result); this.props.change('password',result [0 ] .data); }) .catch(function(error){ console.log('promise error =',error); this.props.change('password','999'); }) ; }; func(this); – Pat

+0

然后出于某种原因,你调用axios的函数没有正确的'this'上下文。使用胖箭头函数只是做'var $ this = this'的一种奇特的方式。 – jakee

+0

非常感谢。 – Pat