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

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

问题描述

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

thissetState 都是未定义的,我无法实现.
有人可以帮我完成这项工作吗?

见截图(下方)

解决方案

JavaScript 中,类方法默认不绑定.
如果忘记绑定 this.LoginApp 并将其传递给 onSubmitthis 在实际调用函数时将是 undefined(正如您已经注意到的).><块引用>

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

一般来说,如果你引用一个没有()的方法,比如onSubmit={this.LoginApp},你应该绑定那个方法.并且为了避免性能问题,一般建议在构造函数中绑定或使用类字段语法.这是来自 React 团队的精彩读物.

constructor(props) {this.state = {...};//这个绑定是让 `this` 在回调中工作所必需的this.LoginApp = this.LoginApp.bind(this);}

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)

解决方案

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

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

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