问题
I am using formik
plugin in reactjs
and I want to useState
variables after form submit.
Both this
and setState
are undefined and I can't achieve it.
Can anybody please help me to get this done?
See screenshot (below)
回答1:
In JavaScript
, class methods are not bound by default.
If you forget to bind this.LoginApp
and pass it to onSubmit
, this
will be undefined
when the function is actually called (as you already noted).
This is not React-specific behavior; it is a part of how functions work in JavaScript.
Generally, if you refer to a method without ()
after it, such as onSubmit={this.LoginApp}
, you should bind that method. And to avoid performance problems, it's generally recommended to bind in the constructor or using the class fields syntax. 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);
}
来源:https://stackoverflow.com/questions/63222406/react-formik-form-how-to-use-state-after-submit-inside-a-callback-function