reactjs - 如何使用 redux-form 处理提交

标签 reactjs redux react-redux redux-form

我正在第一次使用 redux-form。我能够呈现表单,但无法处理提交。虽然我最终想将数据发送到服务器,但此时,我只是尝试控制台记录表单字段值。我收到错误:

错误:您必须向handleSubmit()传递一个onSubmit函数,或者将onSubmit作为prop传递

这是我的 Profile.jsx 文件

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {withAuth} from 'react-devise';
import { Field, reduxForm } from 'redux-form';

class Profile extends Component {
  handleSubmit(data) {
     console.log('Submission received!', data);
   }
  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="firstName">First Name</label>
          <Field name="firstName" component="input" type="text"/>
        </div>
        <div>
          <label htmlFor="lastName">Last Name</label>
          <Field name="lastName" component="input" type="text"/>
        </div>
        <div>
          <label htmlFor="email">Email</label>
          <Field name="email" component="input" type="email"/>
        </div>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

// Decorate the form component
Profile = reduxForm({
  form: 'profile' // a unique name for this form
})(Profile);


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

export default connect(mapStateToProps)(withAuth(Profile));

如何处理提交的值,以便最终将它们发送到我的 API?

最佳答案

Redux-Form 使用 handleSubmit 装饰您的组件支柱。根据文档,它是:

a function meant to be passed to <form onSubmit={handleSubmit}> or to <button onClick={handleSubmit}>. It will run validation, both sync and async, and, if the form is valid, it will call this.props.onSubmit(data) with the contents of the form data.

Optionally, you may also pass your onSubmit function to handleSubmit which will take the place of the onSubmit prop. For example:

因此,如果您的组件没有 onSubmit您必须“手动”将提交处理程序传递给 handleSubmit 的属性功能。请尝试这个:

<form onSubmit={this.props.handleSubmit(this.handleSubmit.bind(this))}>

请不要混淆您的handleSubmit具有从 Redux-Form 传递的同名 prop 的方法。

关于reactjs - 如何使用 redux-form 处理提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43966804/

相关文章:

reactjs - 用 react 钩子(Hook)构建的振荡器不会停止

javascript - React Router 更改参数不会触发 componentWillRecieveProps

react-native - 未在 react-native-router-flux 中传递给 redux 的操作

reactjs - 热重载无法与 React-Redux 和 Hooks 一起正常工作

redux - RTK查询: Transform all query responses at once

javascript - react native : Is it is good to use UI kit for design purpose?

javascript - React componentDidMount 不更新状态

javascript - 如何从数组中渲染随机对象

reactjs - 如何在样式组件中使用 "hover"(CSS) 操作?

reactjs - 在mapDispatchToProps中绑定(bind) Action 参数