React: formik form, how to use state after submit inside a callback function

此生再无相见时 提交于 2020-08-23 04:57:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!