我正在努力使用Redux形式的FieldArray。我在连接带有实际React组件的表单时遇到了挑战。当我尝试提交表单时,出现以下错误:error 'handleSubmit' is not defined

该文件在下面。我可以在我的React组件中正确构建此表单吗?知道为什么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);

最佳答案

您尚未提供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而不是let。

09-18 06:09