javascript - 带有反应和验证器的 Redux 形式

标签 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 形式属性和方法的对象,但错误对象未定义。

我可能会做错事,但我不明白如何以及为什么。

有什么帮助吗?

最佳答案

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

在你的情况下:你的字段“电子邮件”应该进入 props: meta: {error: '这两个电子邮件地址不相同'}

您确定这不会发生吗?

你查过official docs sample?吗?

根据Field docs我知道您只能在字段级别访问它

meta.error : String [optional]

The error for this field if its value is not passing validation. Both synchronous, asynchronous, and submit validation errors will be reported here.

关于javascript - 带有反应和验证器的 Redux 形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41098548/

相关文章:

javascript - 使用组合 reducer 时访问状态的其他部分

javascript - 创建利润计算器

javascript - 除非我删除看似不相关的要求,否则不会导入文件

javascript - React/Redux 链接第二个 API 请求和调度

reactjs - 如何在 React 中调整图像大小

javascript - react : How to supply callback arrow functions to stateless functional child components?

javascript - Redux 异步中间件操作没有 api 调用所需的现有状态

javascript - 用 Sinon 模拟 Redis 构造函数

javascript - 我可以在文档上使用什么来不时应用一个功能,包括 future 的元素?

javascript - React Native/Redux 和react-native-router-flux : Why doesn't Actions. Action 创建者内部的关键工作?