我有一个带有密码字段的 redux-form,在这个简单的示例中尝试使用随机数更新密码字段。如何将“this”绑定(bind)到 Axios 的 catch 函数?
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);
})
.then(function(response) {
//
})
.catch(function(error) {
this.props.change('password', '999');
});
我知道上面的逻辑可以正常工作,因为如果我使用 ES5 var this1 = this;并使用 this1 它工作正常。问候!
最佳答案
您可以使用刚刚描述的方法,即
var $this = this
var func = function() {
$this.props.doSomething()
}
或者你可以
bind
要执行的函数this
语境。在 vanilla JS 中,您可以使用 bind 来完成。 :var func = function() {
this.props.doSomething()
}
// now this inside func will always be whatever it was here
func = func.bind(this)
在 es6 中绑定(bind)
this
arrow functions 简化了匿名函数:const func = () => {
// this will be always whatever it was where this func was defined
this.props.doSomething()
}
希望这可以帮助!
关于reactjs - 将 'this' 传递给 Axios promise 'then' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43397041/