在Formik React表单的handleSubmit方法中设置Redux状态

时间:2019-05-14 18:55:03

标签: reactjs react-redux formik

我想在提交Formik react表单后在Redux存储中设置一个通过Ajax获取的变量

import React from 'react';
import {connect} from 'react-redux';
import { withFormik, Form, Field } from 'formik';

const LoginForm = ({
    values
  }) => {

  return (
        <div>
            <Form className={styles.LoginForm}>
              <Field className={input_classes} type="text" name="username" placeholder="username" />
              <Field className={input_classes} type="password" name="password" placeholder="password" />
              <button>Submit</button>
            </Form>
        </div>
    )

}

const mapDispatchToProps = dispatch => {
  return {
    setData: (data) => dispatch({type: actionTypes.ADD_DATA, data: data})
  }
}

const loginForm = connect(null, mapDispatchToProps)(LoginForm);

const FormikLoginForm = withFormik({
  mapPropsToValues({ username, password }) {
    return {
      username: username || '',
      password: password || '',
    }
  },
  handleSubmit(values, props) {
    //make AJAX call and set data in redux store
  }
})(loginForm);

export default FormikLoginForm;

我找不到在handleSubmit方法中将任何数据设置到存储的方法。也就是说,如何访问返回mapDispatchToProps的setData方法?

1 个答案:

答案 0 :(得分:2)

HOC事务的顺序,尤其是在这种情况下(在另一个HOC中访问prop)-还原connect必须在withFormik之外。

const FormikLoginForm = withFormik({
  mapPropsToValues({ username, password }) {
    return {
      username: username || '',
      password: password || '',
    }
  },
  handleSubmit(values, { props } ) {
    //make AJAX call and set data in redux store
    props.setData( result )
  }
})(LoginForm);

export default connect(null, mapDispatchToProps)(FormikLoginForm);