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

Muh*_*eek 1 reactjs redux redux-form react-redux

我从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;
Run Code Online (Sandbox Code Playgroud)

更新

Dmi*_*rov 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;
Run Code Online (Sandbox Code Playgroud)

来自官方文档的示例- 在这里