reactjs - React & Formik:如何将成功或失败从成功处理程序发送回组件
问题描述
这是关于 formik (反应和打字稿)。
我设法使一些代码工作,但我用.bind(this)
它。我真的认为有更好的方法来做事,所以我在这里问。
这是代码:
public register(values: IRegistrationForm, { setSubmitting, setFieldError }: FormikActions<IRegistrationForm>) {
axios
.post(process.env.REACT_APP_API_URL + '/register', values)
.then(response => {
this.success(); // fail without the bind(this)
setSubmitting(false);
});
}
private formik() {
// I need to bind this to be able to call some methods of my component
const register = this.register.bind(this);
return (
<Formik
initialValues={{
email: '',
password: '',
}}
onSubmit={register}
render= {this.formRender}
validationSchema={Yup.object().shape({
email: Yup.string().email().required(),
password: Yup.string().min(10).required(),
})}
/>
);
}
如果它有帮助(不确定)整个代码在这里:https ://gist.github.com/Nek-/c4ccb6b76593d71105c29079c48757f0
解决方案
最好this
在构造函数中绑定事件处理程序、与关键字共享类上下文的组件函数。不在您的渲染功能中。
constructor(props:Readonly<{}>) {
super(props);
this.state = {
success: null,
};
//... bind your methods here.
this.register = this.register.bind(this)
}
或者使用它会自动绑定this
并避免在渲染或构造函数中绑定的胖箭头函数。
public register = (values: IRegistrationForm, { setSubmitting, setFieldError }: FormikActions<IRegistrationForm>) => {
// your function body.
}
private success = () => {
this.setState({...this.state, success: true});
}
您可以将它与您的fomik
函数或任何需要共享this
上下文的事件处理函数一起使用。
推荐阅读
- amazon-web-services - aws-lambda 没有 S3 触发调用的日志流
- java - 调用 isVisible() 后 JFrame 不显示,没有错误
- windows - 如何将 Github URL 转换为 Windows 和/或 Apple 计算机可以访问的文件路径
- datetime - 转换为字符串时,日期时间的格式仅与一个用户不同
- celery - 本地主机上的 Apache 气流芹菜工人
- c# - 如何在 C# 中使用 MongoDB Compass 生成的管道来运行聚合管道
- c - icmp_hdr 在 CentOS 6 内核上是错误的
- amazon-dynamodb - 如果我不在前端请求,appsync 是否仍会请求关系
- swift - 如何在 UITableViewCell 类中使用为 segue 做准备
- python - 将 N-dim 数组广播到 (N+1)-dim 数组并在除 1 dim 之外的所有数组上求和