如何处理redux表单提交的数据

时间:2016-07-20 09:42:29

标签: reactjs redux react-redux redux-form

我从redux表格官方页面下载本教程 http://redux-form.com/5.3.1/#/getting-started?_k=8q7qyo

我面临两个问题

1:如何在handleSubmit函数或任何其他函数中获取表单数据。这样我就可以根据自己的需要处理表单数据。

2:每当我提交表单时,我的页面都会刷新。我不想刷新我的页面

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';

class ContactForm extends Component {
  render() {
    const {fields: {firstName, lastName, email}, handleSubmit} = this.props;
    return (
      <form onSubmit={handleSubmit}>
        <div>
          <label>First Name</label>
          <input type="text" placeholder="First Name" {...firstName}/>
        </div>
        <div>
          <label>Last Name</label>
          <input type="text" placeholder="Last Name" {...lastName}/>
        </div>
        <div>
          <label>Email</label>
          <input type="email" placeholder="Email" {...email}/>
        </div>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

ContactForm = reduxForm({ // <----- THIS IS THE IMPORTANT PART!
  form: 'contact',                           // a unique name for this form
  fields: ['firstName', 'lastName', 'email'] // all the fields in your form
})(ContactForm);

export default ContactForm;

更新

1 个答案:

答案 0 :(得分:5)

在提交表单时,有两种方法可以让redux-form函数运行:

  • 将其作为onSubmit道具传递给您的装饰组件。在这种情况下,您可以在装饰组件中使用onClick={this.props.handleSubmit},以便在单击提交按钮时触发它。
  • 将其作为参数传递给装饰组件内的this.props.handleSubmit函数。在这种情况下,您可以在装饰组件中使用onClick={this.props.handleSubmit(mySubmit)},以便在单击提交按钮时触发它。

重构的例子:

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';

class ContactForm extends Component {
  submit(formValues) {
    console.log(formValues);
  }
  render() {
    const {fields: {firstName, lastName, email}, handleSubmit} = this.props;
    return (
      <form onSubmit={handleSubmit(this.submit)}>
        <div>
          <label>First Name</label>
          <input type="text" placeholder="First Name" {...firstName}/>
        </div>
        <div>
          <label>Last Name</label>
          <input type="text" placeholder="Last Name" {...lastName}/>
        </div>
        <div>
          <label>Email</label>
          <input type="email" placeholder="Email" {...email}/>
        </div>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

ContactForm = reduxForm({ // <----- THIS IS THE IMPORTANT PART!
  form: 'contact',                           // a unique name for this form
  fields: ['firstName', 'lastName', 'email'] // all the fields in your form
})(ContactForm);

export default ContactForm;

官方文档示例 - here