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

IT技术 reactjs redux react-redux redux-form
2021-05-14 04:46:43

我从 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个回答

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

  • 将它作为onSubmitprops传递给您的装饰组件。在这种情况下,您将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;

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