Redux表单 - 您必须将handleSubmit()传递给onSubmit函数或传递onSubmit作为prop

时间:2017-07-26 09:29:05

标签: javascript reactjs redux-form

我想创建一个简单的表单,其中包含一个电子邮件地址,然后将其添加到我们的数据库中。我使用了React Forms,因为它有利于整个开发过程并减少了时间。

但是,当我尝试POST我的表单时,我收到此错误:未捕获错误:您必须传递handleSubmit()一个onSubmit函数或传递onSubmit作为prop

这是我的 AddUserForm.js

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

const AddUserForm = ({ handleSubmit }) => {
  return (
    <form onSubmit={handleSubmit}>
      <div>
        <Field name="email" component="input" type="email" />
      </div>
      <button type="submit">Bjud in</button>
    </form>
  )
}
export default reduxForm({
  form: 'addUser'
})(AddUserForm)

这是我的 addUserAction

import axios from 'axios'
import settings from '../settings'

axios.defaults.baseURL = settings.hostname

export const addUser = email => {
  return dispatch => {
    return axios.post('/invite', { email: email }).then(response => {
      console.log(response)
    })
  }
}

这是我的 AddUserContainer.js:

import React, { Component } from 'react'
import { addUser } from '../../actions/addUserAction'
import AddUserForm from './Views/AddUserForm'
import { connect } from 'react-redux'

class AddUserContainer extends Component {
  submit(values) {
    console.log(values)
    this.props.addUser(values)
  }

  render() {
    return (
      <div>
        <h1>Bjud in användare</h1>
        <AddUserForm onSubmit={this.submit.bind(this)} />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return { user: state.user }
}

export default connect(mapStateToProps, { addUser })(AddUserContainer)

感谢阅读!

1 个答案:

答案 0 :(得分:2)

onSubmit 未定义,因为它未声明。按照路径:

注意values变量包含字段数据,在您的情况下,它会保存键入的电子邮件。

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

const AddUserForm = ({ handleSubmit }) => {
  return (
    <form onSubmit={handleSubmit}>
      <div>
        <Field name="email" component="input" type="email" />
      </div>
      <button type="submit">Bjud in</button>
    </form>
  )
}

const onSubmit = (values, dispatch) => {
  dispatch(    // your submit action //      );
};

export default connect()(reduxForm({
  form: 'addUser', 
  onSubmit, 
})(AddUserForm));