我正在使用redux-form 6.3版本,并在此验证函数中被调用。下面是我的代码。请检查代码中的问题。
还需要进行与行动验证相关的更改
import React, { Component } from 'react';
import { Field, reduxForm, initialize } from 'redux-form';
import { connect } from 'react-redux';
import * as actions from '../../actions';
const renderField = field => (
<div className="form-group">
<label>{field.input.label}</label>
<input {...field.input} value={field.value} onChange={(e)=> console.log(e.target.value) } />
{field.touched && field.error && <div className="error">{field.error}</div>}
</div>
);
const renderSelect = field => (
<div>
<label>{field.input.label}</label>
<select {...field.input}/>
{field.touched && field.error && <div className="error">{field.error}</div>}
</div>
);
function validate(formProps) {console.log("vvv---", formProps);
const errors = {};
if (!formProps.firstName) {
errors.firstName = 'Please enter a first name';
}
if (!formProps.lastName) {
errors.lastName = 'Please enter a last name';
}
if (!formProps.email) {
errors.email = 'Please enter an email';
}
if (!formProps.phoneNumber) {
errors.phoneNumber = 'Please enter a phone number'
}
if(!formProps.sex) {
errors.sex = 'You must enter your sex!'
}
return errors;
}
class ReduxFormTutorial extends Component {
componentDidMount() {
this.handleInitialize();
}
handleInitialize() {
const initData = {
"firstName": "Puneet",
"lastName": "Bhandari",
"sex": "male",
"email": "test@gmail.com",
"phoneNumber": "23424234"
};
this.props.initialize(initData);
}
handleFormSubmit(formProps) {
//console.log(formProps);
this.state = { firstName : null };
this.props.submitFormAction(formProps);
}
//our other functions will go here
render() {
const { fields : [firstName, lastName], handleSubmit } = this.props;
return (
<div>
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<Field name="firstName" value="" type="text" component={renderField} label="First Name" />
<Field name="lastName" value="" type="text" component={renderField} label="Last Name"/>
<Field name="sex" component={renderSelect} label="Gender">
<option></option>
<option name="male">Male</option>
<option name="female">Female</option>
</Field>
<Field name="email" type="email" component={renderField} label="Email" />
<Field name="phoneNumber" type="tel" component={renderField} label="Phone Number"/>
<button action="submit">Save changes</button>
</form>
</div>
)
}
}
const form = reduxForm({
form: 'ReduxFormTutorial',
fields: [ 'firstName', 'lastName' ],
validate
});
function mapStateToProps(state) {
return {
user: state.user
};
}
export default connect(mapStateToProps, actions)(form(ReduxFormTutorial));