如何将Redux与antd表单验证集成

时间:2019-04-05 07:18:48

标签: reactjs react-redux antd

我正在使用react-js,antd和redux验证电子邮件字段,我的问题是为什么当我集成redux(created-form.js)时,输入中的加载图标消失了,但是当我删除redux集成时,加载图标工作正常,我是否在这里丢失了东西,或者做了不正确的事情?

base-form.js

 ...

 // Constructor

 constructor() {
   super();

   this._validateEmail = _.debounce(this._validateEmail, 1000);
 }


 // Private method

 _validateEmail = (rule, email, callback) => {
   const url = 'http://localhost:8000/api/user/isExist';

   axios
     .post(url, { email })
     .then(res => {
       if (res.data.isExist) {
         callback('Email is already exist');
       }

       callback();
     })
     .catch(res => console.log(res));
 };


 // Render

 <Form.Item hasFeedback>
    {getFieldDecorator('email', {
       rules: [...rules.email, { validator: this._validateEmail }]
    })(<Input placeholder="Email" />)}
 </Form.Item>

...

created-form.js

  import { Form } from 'antd';
  import AccSetupForm from './base-form';

  function mapPropsToFields(props) {
    return {
      email: Form.createFormField({
        value: props.email
      }),
      password: Form.createFormField({
        value: props.password
      }),
      confirm_pass: Form.createFormField({
        value: props.confirm_pass
      })
    };
  }

  function onFieldsChange(props, changedField) {
    const field = Object.values(changedField)[0];

    if (field !== undefined) {
      props.updateAccSetup({
        [field.name]: field.value
      });
    }
  }

  const CreatedForm = Form.create({ mapPropsToFields, onFieldsChange })(
    AccSetupForm
  );

  export default CreatedForm;

index.js

import { connect } from 'react-redux';
import { updateAccSetup } from '../actions';
import CreatedForm from './created-form';

function mapStateToProps(state) {
   return {
    email: state.getIn(['registration', 'user', 'email']),
    password: state.getIn(['registration', 'user', 'password']),
    confirm_pass: state.getIn(['registration', 'user', 'confirm_pass'])
  };
}

function mapDispatchToProps(dispatch) {
  return {
    updateAccSetup: userInfo => dispatch(updateAccSetup(userInfo))
  };
}

const StepOne = connect(
  mapStateToProps,
  mapDispatchToProps
)(CreatedForm);

export default StepOne;

1 个答案:

答案 0 :(得分:0)

我发现了问题,我忘记在...props.username内添加form.createFormField

/* Antd Docu */

 mapPropsToFields(props) {
   return {
     username: Form.createFormField({
       ...props.username,
       value: props.username.value,
     }),
   };
},

这里有一些参考: https://github.com/ant-design/ant-design/issues/9561 https://ant.design/components/form/#components-form-demo-global-state