gpt4 book ai didi

javascript - 验证 Redux 表单 : Nested Values

转载 作者:行者123 更新时间:2023-11-30 20:08:11 24 4
gpt4 key购买 nike

我在 ReduxForm 中进行验证,直到我必须验证名称嵌套的字段,即:location.coordinates[0]

这个数据在 Redux Store 中看起来像这样:

"location" : {
"type" : "Point",
"coordinates" : [
103.8303,
4.2494
]
},

当尝试使用

验证此类字段时

方法一

if (!values.location.coordinates[0]) {
errors.location.coordinates[0] = 'Please enter a longtitude';
}

我遇到错误:

TypeError: Cannot read property 'coordinates' of undefined

方法二

if (values.location !== undefined) {
errors.location.coordinates[0] = 'Please enter a longtitude';
errors.location.coordinates[1] = 'Please enter a latitude';
}

我遇到错误:

TypeError: Cannot read property 'coordinates' of undefined

问题:处理此类字段的正确方法是什么?

/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: []
}
}

关于javascript - 验证 Redux 表单 : Nested Values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52650033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com