【问题标题】:React & Formik : how to send back sucess or failure from sucess handler to the componentReact & Formik:如何将成功或失败从成功处理程序发送回组件
【发布时间】:2018-12-01 17:01:23
【问题描述】:

这是关于 formik (react & typescript)。

我设法让一些代码正常工作,但我为此使用了.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

【问题讨论】:

    标签: reactjs typescript formik


    【解决方案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 上下文的事件处理函数一起使用。

    【讨论】:

    • 好吧,我想避免它,而不是改变方法。同样,这对我来说准备一个绑定到 this while 的方法也没有任何意义……这实际上是默认行为!
    • 我希望得到一个可以真正帮助我将信息转发到“上一个”组件的答案。但是您的解决方案是真实的。测试,工作。谢谢。
    猜你喜欢
    • 2015-03-25
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 2020-01-16
    • 2021-08-07
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    相关资源
    最近更新 更多