【发布时间】:2018-02-14 00:10:11
【问题描述】:
我正在尝试创建一个验证函数,如果客户端输入错误或服务器返回错误,该函数会返回错误。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Form, submit, reduxForm, Field } from 'redux-form';
import Modal from '../../ui/modal';
import { ACCOUNT_REGISTER_MODAL_ID } from './constants';
import registerRequest from './actions';
import CField from '../../ui/form/field';
function validate(values, props) {
const errors = {};
console.log('-');
console.log(values);
console.log(props);
console.log('-');
if (!errors.description && (!values.description || values.description.trim() === '')) {
errors.description = 'Enter a Description';
}
if (!errors.username && (!values.username || values.username.trim() === '')) {
errors.username = 'Enter a Username';
}
return errors;
}
class RegisterModal extends Component {
static propTypes = {
handleSubmit: PropTypes.func,
fields: PropTypes.array,
register: PropTypes.shape({
requesting: PropTypes.bool,
successful: PropTypes.bool,
messages: PropTypes.array,
errors: PropTypes.array,
fieldErrors: PropTypes.array,
}),
dispatch: PropTypes.func,
};
onSubmit = (values) => {
console.log(this.props);
console.log(values);
}
getForm = () => {
this.props.dispatch(submit('register'));
}
render() {
const {
handleSubmit,
fields,
register: {
requesting,
successful,
messages,
errors,
fieldErrors,
},
} = this.props;
console.log(fieldErrors);
const required = value => value ? undefined : 'Required';
return (
<Modal
modalID={ACCOUNT_REGISTER_MODAL_ID}
header={'Connect Account'}
submitText={'Connect'}
onSubmitClick={this.getForm}
register={this.register}
>
<Form
className="ui form register"
onSubmit={handleSubmit(this.onSubmit)}
fieldErrors={fieldErrors}
>
<Field
name="description"
type="text"
component={CField}
label="Please give a recognizable name to this account"
required
placeholder="My main Account"
/>
<Field
name="username"
type="text"
component={CField}
label="Please enter your username"
required
placeholder="foobar2017"
/>
</Form>
</Modal>
);
}
}
const mapStateToProps = state => ({
register: state.RegisterModal,
});
const connected = connect(mapStateToProps, { registerRequest })(RegisterModal);
const formed = reduxForm({
form: 'register',
fields: ['description', 'username'],
validate
})(connected);
export default formed;
传递给验证函数的值似乎都不包含我传递给表单组件的“fieldErrors”道具。我需要能够将 prop 传递给 validate 函数,这样我才能访问通过 redux 接收到的来自服务器的响应。
我应该以不同的方式创建我的验证函数吗?
【问题讨论】:
-
你不需要
fieldErrors={fieldErrors}而不是fieldErrors={this.fieldErrors}吗? -
根据文档,
validate应该是(values: Object, props: Object) => Object?类型,我的意思是 2 个参数,而不是 3 个,props是第二个。 -
@YuryTarabanko 我更改了验证功能以在单个字段组件而不是表单上对其进行测试,但无论哪种方式,即使我将其更改为 API 所说的那样,它仍然没有通过自定义支撑起来。 this.fieldErrors 也不正确,但更正它仍然不会使其冒泡到 validate 函数。
-
文档说您可以将
props属性添加到Field,但是在记录字段的验证道具时,自定义道具不会合并。props有什么用?
标签: reactjs react-redux redux-form