Redux形式与反应和验证器

时间:2016-12-12 10:17:47

标签: javascript reactjs redux redux-form

我是第一次使用redux表单而且我遇到了处理同步验证器的麻烦。

实际上,我有以下内容:

import React, {Component, PropTypes} from 'react';
import {Field} from 'redux-form';
/**
 * The SignupForm class definition
 */
export default class SignupForm extends Component {
    /**
     * The SignupForm props type
     */
    static propTypes = {
        handleSubmit: PropTypes.func,
    }

    /**
     * Render the SignupForm
     */
    render() {
        console.log(this.props); // nothing available concerning the error
        const {
            handleSubmit
        } = this.props;
        return (
            <form onSubmit={handleSubmit}>
                <Field name="email" component="input" required placeholder="Email" type="text"/>
                <Field name="emailConfirmation" component="input" required placeholder="Confirm your email" type="text"/>
                <Field name="password" component="input" required placeholder="Password" type="password"/>
                <Field name="passwordConfirmation" component="input" required placeholder="Confirm your password" type="password"/>
                <button type="submit" className="signup">Signup</button>
            </form>
        );
    }
}

以下验证器:

export default ({email, emailConfirmation}) => {
    const errors = {
        email: null
    };

    if (email !== emailConfirmation) {
        errors.email = 'The two email addresses are not the same';
    }
    console.log(errors); // the error is here
    return errors;
};

使用reduxForm函数映射redux表单和验证器:

import SignupForm from './../../components/signupForm/signupForm';
import validate from './signupForm.validators';
import {reduxForm} from 'redux-form';
export default reduxForm({
    form: 'signup',
    validate
})(SignupForm);

我的问题

当我在验证器中的console.log中返回语句中的错误对象时,我的错误告诉我的电子邮件地址不一样。

但是当我在我的组件中使用console.log this.props 时,我可以看到一个带有一些redux-form属性和方法的对象,但错误对象是未定义的。

我可能会把事情弄错,但我不知道如何以及为什么。

任何帮助?

1 个答案:

答案 0 :(得分:2)

当你的validate函数被调用时,你正在创建一个对象“errors”并返回它,所以redux-form将使用它来向相应的字段注入错误。

在您的情况下:您的字段“电子邮件”应该包含道具:meta:{错误:'两个电子邮件地址不一样'}

你确定这不会发生吗?

您检查了official docs sample?

吗?

根据Field docs我知道你只能在现场级别

  

meta.error:String [可选]

     

如果此字段的值未通过验证,则为该字段的错误。同步,异步和提交验证错误都将在此处报告