Redux-form FieldArray,handleSubmit'没有定义

时间:2017-06-09 04:48:32

标签: reactjs redux react-redux redux-form

我正在努力使用redux-form FieldArray。我在挑战实际反应组件的形式时遇到了挑战。当我尝试提交表单时,出现以下错误:error 'handleSubmit' is not defined

下面的文件...我是否在我的反应组件中正确构建此表单?知道为什么handleSubmit出错了吗?感谢

import React from 'react';
import {Field, FieldArray, reduxForm} from 'redux-form'
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as inviteActions from '../../actions/inviteActions';

let renderEmailField = ({input, label, type, meta: {touched, error}}) =>
  <div>
    <label>{label}</label>
    <div>
      <input {...input} name="email" type="email"/>
      {touched && error && <span>{error}</span>}
    </div>
  </div>

let renderEmails = ({fields, meta: {submitFailed, error}}) =>
  <ul>
    <li>
      <button type="button" onClick={() => fields.push()}>Add Email</button>
    </li>
    {fields.map((email, index) =>
      <li key={index}>
        {index > 2 && <button
          type="button"
          title="Remove Email"
          onClick={() => fields.remove(index)}
        />}
        <Field
          name={email}
          component={renderEmailField}
          label={`Email #${index + 1}`}
        />
      </li>
    )}
    {submitFailed && error && <li className="error">{error}</li>}
  </ul>

let EmailsForm = ({handleSubmit, pristine, reset, submitting}) =>
  <form onSubmit={handleSubmit}>
    <FieldArray name="emails" component={renderEmails} />
    <div>
      <button type="submit" disabled={submitting}>Submit</button>
      <button type="button" disabled={pristine || submitting} onClick={reset}>
        Clear Values
      </button>
    </div>
  </form>


class InvitePage extends React.Component {

  handleSubmit(data) {
    console.log(data)
    this.props.actions.createInvites(data);
  }

  render() {

    return (
      <div>
        <h1>Invites</h1>
        <EmailsForm onSubmit={handleSubmit}/>
      </div>
    );
  }

}

EmailsForm = reduxForm({
  form: 'emailsForm',
  initialValues: {
    emails: ['', '', '']
  },
  validate(values) {
    const errors = {}
    if (!values.emails || !values.emails.length) {
      errors.emails = {_error: 'At least one email must be entered'}
    }
    else {
      let emailsArrayErrors = []
      values.emails.forEach((email, emailIndex) => {
        const emailErrors = {}
        if (email == null || !email.trim()) {
          emailsArrayErrors[emailIndex] = 'Required'
        }
      })
      if (emailsArrayErrors.length) {
        errors.emails = emailsArrayErrors
      }
    }
    return errors
  }
})(EmailsForm)

const mapStateToProps = state => {
  return {
    currentUser: state.currentUser
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(inviteActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(InvitePage);

2 个答案:

答案 0 :(得分:3)

您尚未提供onSubmit函数作为EmailsForm的道具。您可以通过两种方式传递它:

EmailsForm = reduxForm({
  form: 'emailsForm',
  ...
  onSubmit: () => {}
  ... 
})(EmailsForm)

或者您可以在调用onSubmit

时将EmailsForm作为道具传递
<EmailsForm onSubmit={() => {}} />

在你的情况下,你必须这样写:

<EmailsForm onSubmit={this.handleSubmit.bind(this)}/>

据我所知,如果您可以重复使用这些小组件renderEmailField, renderEmails, EmailsForm,那么您可以像现在一样将它们创建为单独的组件。

我建议您不要将EmailsForm与InvitePage类分开,因为随着需求的增长,您必须将所有道具从InvitePage传递到EmailsForm。除了传递onSubmit函数之外,InvitePage目前不提供任何其他目的。

class InvitePage extends React.Component {

  handleSubmit = data => {
    console.log(data)
    this.props.actions.createInvites(data);
  }

  render() {
    const { pristine, reset, submitting } = this.props
    return (
      <div>
        <h1>Invites</h1>
        <form onSubmit={this.handleSubmit}> // react recommends we should not bind function here. Either bind that in constructor or write handleSubmit like I have written.
          <FieldArray name="emails" component={renderEmails} />

          <div>
            <button type="submit" disabled={submitting}>Submit</button>
            <button type="button" disabled={pristine || submitting} onClick={reset}>
              Clear Values
            </button>
          </div>
        </form>
      </div>
    )
  }

}

InvitePage = reduxForm({
  form: 'emailsForm',
  initialValues: {
    emails: ['', '', ''],
  },
  validate(values) {
    ...
  }
})(InvitePage)

希望它有效。

如果您没有更改任何变量的值,请尝试使用 const 而不是

答案 1 :(得分:2)

你必须显式地将回调函数传递给handleSubmit。

render() {
    const { handleSubmit } = this.props;


    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
          <Field name="firstName" component={this.renderField} type="text" className="curvedBorder" label="First Name" />
          ...
          <button type="submit" className="btn btn-primary">Submit</button>
      </form>
    );
}


onSubmit(values) {
    // handle form submission here.
    console.log(values);
}

希望这会有所帮助。快乐的编码!