我在ReduxForm中有validatioin工作,直到我必须验证名称嵌套的字段,即:location.coordinates[0]
。
此数据在 Redux 存储中如下所示:
"location" : {
"type" : "Point",
"coordinates" : [
103.8303,
4.2494
]
},
尝试使用 验证此类字段时
方法1
if (!values.location.coordinates[0]) {
errors.location.coordinates[0] = 'Please enter a longtitude';
}
我收到错误:
类型错误: 无法读取未定义的属性"坐标">
方法2
if (values.location !== undefined) {
errors.location.coordinates[0] = 'Please enter a longtitude';
errors.location.coordinates[1] = 'Please enter a latitude';
}
我收到错误:
类型错误: 无法读取未定义的属性"坐标">
问题:处理此类字段的正确方法是什么?
/src/containers/Animals/AnimalForm.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { reduxForm, Field } from 'redux-form';
import { renderTextField } from './FormHelpers';
class AnimalForm extends Component {
render() {
return (
<div>
<form onSubmit={ this.props.handleSubmit }
<Field
label="Longitude"
name="location.coordinates[0]"
component={renderTextField}
type="text"
/>
<Field
label="Latitude"
name="location.coordinates[1]"
component={renderTextField}
type="text"
/>
</form>
</div>
)
}
}
const validate = values => {
let errors = {}
if (values.location !== undefined) {
errors.location.coordinates[0] = 'Please enter a longtitude';
errors.location.coordinates[1] = 'Please enter a latitude';
}
if ((values.location !== undefined) && (values.location.coordinates !== undefined)) {
errors.location.coordinates[0] = 'Please enter a longtitude';
errors.location.coordinates[1] = 'Please enter a latitude';
}
return errors;
}
function mapStateToProps(state) {
return { ... }
}
export default connect(mapStateToProps)(reduxForm({
form: 'animal',
validate
})(AnimalForm))
/src/containers/Animals/FormHelper.js
import React from 'react';
import { FormGroup, Label, Input, Alert } from 'reactstrap';
export const renderTextField = ({input, type, meta: {touched, error}, ...custom}) => (
<div>
<Label>{ label }</Label>
<Input
type={type}
value={input.value}
onChange={input.onChange}
/>
{touched && error && <Alert color="warning">{ error }</Alert>}
</div>
)
在验证方法中,如何构建初始错误对象:
let errors = {
location: {
coordinates: []
}
}
以下解决方案将起作用
const validate = values => {
let errors = values;
if(values){
if (values.location) {
errors.location.coordinates[0] = 'Please enter a longtitude';
errors.location.coordinates[1] = 'Please enter a latitude';
}
}
return errors;
}