React:formik 表单,如何在回调函数内提交后使用状态
React: formik form, how to use state after submit inside a callback function
我在 reactjs
中使用 formik
插件,我想在表单提交后 useState
变量。
this
和setState
都未定义,我无法实现。
有人可以帮我完成这个吗?
查看屏幕截图(下)
在JavaScript
中,class方法默认不绑定。
如果忘记绑定this.LoginApp
并将其传递给onSubmit
,this
将在实际调用函数时 undefined
(正如您已经注意到的那样)。
This is not React-specific behavior; it is a part of how functions work in JavaScript.
一般来说,如果你引用的方法后面没有()
,比如onSubmit={this.LoginApp}
,你应该绑定那个方法。为了避免性能问题,通常建议在构造函数中绑定或使用 class 字段语法。 Here's a good read from the react team.
constructor(props) {
this.state = {...};
// This binding is necessary to make `this` work in the callback
this.LoginApp = this.LoginApp.bind(this);
}
我在 reactjs
中使用 formik
插件,我想在表单提交后 useState
变量。
this
和setState
都未定义,我无法实现。
有人可以帮我完成这个吗?
查看屏幕截图(下)
在JavaScript
中,class方法默认不绑定。
如果忘记绑定this.LoginApp
并将其传递给onSubmit
,this
将在实际调用函数时 undefined
(正如您已经注意到的那样)。
This is not React-specific behavior; it is a part of how functions work in JavaScript.
一般来说,如果你引用的方法后面没有()
,比如onSubmit={this.LoginApp}
,你应该绑定那个方法。为了避免性能问题,通常建议在构造函数中绑定或使用 class 字段语法。 Here's a good read from the react team.
constructor(props) {
this.state = {...};
// This binding is necessary to make `this` work in the callback
this.LoginApp = this.LoginApp.bind(this);
}