reactjs - 将 'this' 传递给 Axios promise 'then' ?

标签 reactjs redux-form

我有一个带有密码字段的 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/

相关文章:

reactjs - 在通用 Typescript React 组件上使用 HOC

typescript - TS2339 : Property does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<FormInstance<{}, Partial<ConfigProps<{}, {}>>>> & ...'

reactjs - 如何在页面上多次嵌入相同的 redux-form ?

javascript - Redux-Form 使用 "client"表单同时创建和编辑时出现问题

reactjs - 健全性查询不会一致地返回更新的数据

javascript - 如何在 React 中触发 onBlur 事件?

javascript - 刷新页面时无法获取 `beforeunload`事件中的当前状态值?

android - 如何从我的 Android 代码在 Web View 中运行 React JS 函数?

reactjs - 一个组件中的多个表单无法识别表单和初始值属性(redux-form v7.0.4)

javascript - react : checker is not a function