问题
I want to create a simple form that takes in an email adress and later adds it to our database. I went with React Forms, because it facilitates the whole development process and reduces the amount of time.
However, when I'm trying to POST my form I'm getting this error: Uncaught Error: You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop
Here's my 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)
Here's my 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)
})
}
}
And here's my 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)
Thanks for reading!
回答1:
onSubmit
is not defined because it's not declared. Follow the path:
Note: values
variable holds fields data, in your case it will hold typed email.
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));
来源:https://stackoverflow.com/questions/45322860/redux-form-you-must-either-pass-handlesubmit-an-onsubmit-function-or-pass-on