首页 文章

Redux形式与反应和验证器

提问于
浏览
0

我是第一次使用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);

My problem

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

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

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

有帮助吗?

1 回答

  • 2

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

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

    你确定这不会发生吗?

    你看过official docs sample?

    根据Field docs我明白你只能在Field级别上进行

    meta.error:String [可选]如果此字段的值未通过验证,则为该字段的错误 . 此处将报告同步,异步和提交验证错误 .

相关问题