React:Formik表单,回调函数内部提交后如何使用状态 [英] React: formik form, how to use state after submit inside a callback function

查看:146
本文介绍了React:Formik表单,回调函数内部提交后如何使用状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在reactjs中使用formik插件,我想在表单提交后使用useState变量.

I am using formik plugin in reactjs and I want to useState variables after form submit.

thissetState都未定义,我无法实现.
有人可以帮我解决这个问题吗?

Both this and setState are undefined and I can't achieve it.
Can anybody please help me to get this done?

请参见下面的屏幕截图

See screenshot (below)

推荐答案

JavaScript中,默认情况下未绑定类方法.
如果忘记绑定this.LoginApp并将其传递给onSubmit,实际调用该函数时(如您已经提到的),this将为undefined.

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).

这不是特定于React的行为;这是函数在JavaScript中如何工作的一部分.

This is not React-specific behavior; it is a part of how functions work in JavaScript.

通常,如果引用的方法后面没有(),例如onSubmit={this.LoginApp},则应绑定该方法.为了避免性能问题,通常建议绑定到构造函数中或使用类字段语法. 这是React团队的好读物.

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);
}

这篇关于React:Formik表单,回调函数内部提交后如何使用状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆