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它工作正常。
问候!
我做了一个改变,并使用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
然后出于某种原因,你调用axios的函数没有正确的'this'上下文。使用胖箭头函数只是做'var $ this = this'的一种奇特的方式。 – jakee
非常感谢。 – Pat