首页 > 解决方案 > 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

标签: reactjstypescriptformik

解决方案


最好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上下文的事件处理函数一起使用。


推荐阅读