React&Formik:如何将成功或失败从成功处理程序发送回组件

时间:2018-12-01 17:01:23

标签: reactjs typescript 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

1 个答案:

答案 0 :(得分:1)

最好绑定事件处理程序,与构造函数中的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上下文的任何事件处理函数一起使用。