【问题标题】:Redux form with react and validators带有反应和验证器的 Redux 表单
【发布时间】:2017-04-27 04:23:23
【问题描述】:

我是第一次使用 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 在我的验证器中返回语句中的 errors 对象 时,我很高兴我的错误告诉我我的电子邮件地址不一样。

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

我可能做错了,但我不知道怎么做以及为什么。

有什么帮助吗?

【问题讨论】:

    标签: javascript reactjs redux redux-form


    【解决方案1】:

    当您的验证函数被调用时,您正在创建一个对象“错误”并返回它,因此 redux-form 将使用它来将错误注入相应的字段。

    在您的情况下:您的字段“电子邮件”应该进入道具:元:{错误:'两个电子邮件地址不相同'}

    你确定这不会发生吗?

    你查过official docs sample?

    根据Field docs,我知道您只能在现场级别访问它

    meta.error : 字符串 [可选]

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

    【讨论】:

    • 哦,这只是在字段级别?如果我需要在表单级别实现它怎么办?
    • 我想是的,如果您需要这样做,您可能希望将引用保存到这些字段并从父级创建可调用函数。或者你可以将它存储在 redux 中并使用选择器。看你的需求
    • 您可以在_error 键处创建表单级错误。即errors._error = 'Something wrong with whole form';
    猜你喜欢
    • 2021-07-17
    • 2018-09-08
    • 2020-05-15
    • 2022-01-04
    • 2018-07-08
    • 2020-01-17
    • 2022-10-18
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多