Redux-form:在页面顶部显示错误列表 [英] Redux-form: display a list of errors on top of a page

查看:39
本文介绍了Redux-form:在页面顶部显示错误列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以改变输入颜色的方式使用 Redux-form在页面顶部显示实际错误.如何访问字段本身之外的当前字段错误列表?

解决方案

您无法从提供给 Field 组件的渲染函数外部获取错误列表.这是因为错误没有存储在 redux 存储中.

编辑 26/12/2018 :

这个答案需要一些时间.ReduxForm 现在将错误存储在 Redux 存储中.看看 @nicoqh 的答案,它使用 ReduxForm 的选择器在任何 Redux 连接组件中获取错误.

这个答案并没有完全过时,但它不再是实现这个恕我直言的最干净的方法.

解决方案1:对同一个值使用多个字段

第一个解决方案是对同一个值使用多个 Field 实例.如果多个 Field 组件具有相同的名称并连接到相同的表单名称,它们将全部连接到相同的值和相同的错误处理.

因此您可以使用 Field 组件并仅呈现错误.

从 'react' 导入 React从redux-form"导入 {reduxForm}const renderError = ({input, meta, ...props}) =>(<span {...props} className='error'>错误:{meta.error}</span>)const renderInput = ({input, meta, ...props}) =>(<input {...input} {...props} className={meta.error ?'错误':空}/>)const FormWithError = ({handleSubmit}) =>(<div>

<Field name='myInput' component={renderError}/>

<form onSubmit={handleSubmit}><Field name='myInput' component={renderInput}/></表单>

)const validate = (values, props) =>{常量错误 = {}/* 通过将它们附加到错误对象来计算这里的错误 */返回错误}导出默认 reduxForm({form: 'myForm', validate})(FormWithError)

解决方案 2:使用全局错误属性

第二种解决方案是使用全局错误道具,但您必须使用 reduxForm 显示来自容器组件的错误.

注意这是一个完全的反模式!全局错误道具用于独立于字段的错误.

从 'react' 导入 React从redux-form"导入 {reduxForm}const renderInput = ({input, meta, ...props}) =>(<input {...input} {...props} className={meta.error ?'错误':空}/>)const FormWithError = ({handleSubmit, error}) =>(<div>

<span {...props} className='error'>错误:{error}</span>

<form onSubmit={handleSubmit}><Field name='myInput' component={renderInput}/></表单>

)const validate = (values, props) =>{常量错误 = {}/* 通过将它们附加到错误对象来计算这里的错误 */if(Object.keys(errors) > 0) {//您可以将每个错误连接到一个字符串中for(key in errors) errors._error += key + ': ' + errors[key]//或juste将错误对象放在全局错误属性中错误._错误 = {...错误}}返回错误}导出默认 reduxForm({form: 'myForm', validate})(FormWithError)

解决方案 3:从商店获取错误

您总是可以通过将验证函数应用于存储中的值来从存储中获取错误.它对于大量验证可能没有性能,因为它在每次渲染时都运行验证,因此当值更改时它运行两次,如果其他一些 props 更改则运行一次.使用异步验证也很困难.

从 'react' 导入 React从redux-form"导入 {reduxForm, formValueSelector}从redux"导入 {connect}const renderErrors = 错误 =>{const errorNodes = []for(key in errors) errorNodes.push(<span className='error'>{key}: {errors[key]}</span>)返回错误节点}const renderInput = ({input, meta, ...props}) =>(<input {...input} {...props} className={meta.error ?'错误':空}/>)让 FormWithError = ({handleSubmit, values, ...otherProps}) =>(<div>

{renderErrors(validate(values, otherProps))}

<form onSubmit={handleSubmit}><Field name='myInput1' component={renderInput}/><Field name='myInput2' component={renderInput}/></表单>

)const validate = (values, props) =>{常量错误 = {}/* 通过将它们附加到错误对象来计算这里的错误 */返回错误}FormWithError = reduxForm({form: 'myForm', validate})(FormWithError)FormWithError = 连接(状态 =>formValueSelector('myForm')(state, 'myInput1', 'myInput2'))(FormWithError)

<块引用>

最后一个解决方案是通过实现 componentWillReceiveProps 并分派一个动作来更新 store 中的错误列表来将错误存储在 store 中,但我认为这不是一个好主意.最好保留简单的无状态组件来渲染 Field 组件.

编辑 26/12/2018 :

在我发布时,这最后一个解决方案"并不是一个好的解决方案.但是由于 componentWillReceiveProps 在 React 中被弃用,它根本不是解决方案.请不要在您的应用程序中执行此操作.我不会删除历史记录,以防此答案链接到某处.

I want to use Redux-form in a manner that changes input color & displays the actual error on top of the page. How do I access the list of current field errors outside the fields themselves?

解决方案

You can't get the list of errors from outside of the render function given to the Field component. This is because errors are not stored in the redux store.

EDIT 26/12/2018 :

This answer is taking some age. ReduxForm now stores errors in the Redux store. Take a look to @nicoqh's answer which is using ReduxForm's selectors to get errors in any Redux connected component.

This answer is not totaly obsolete but it's not anymore the cleanest way to achieve this imho.

Solution 1: Use multiple Field for the same value

The first solution is to use multiple instance of Field for the same value. If multiple Field components have the same name and is connected to the same form name, they will all be connected to the same value and the same error handling.

So you can use a Field component and only render the error.

import React from 'react'
import {reduxForm} from 'redux-form'

const renderError = ({input, meta, ...props}) => (
    <span {...props} className='error'>Error : {meta.error}</span>
)

const renderInput = ({input, meta, ...props}) => (
    <input {...input} {...props} className={meta.error ? 'error' : null} />
)

const FormWithError = ({handleSubmit}) => (
    <div>
        <div className='errorContainer'>
            <Field name='myInput' component={renderError} />
        </div>
        <form onSubmit={handleSubmit}>
            <Field name='myInput' component={renderInput} />
        </form>
    </div>
)

const validate = (values, props) => {
    const errors = {}
    /* calculate errors here by appending theim to errors object */
    return errors
}

export default reduxForm({form: 'myForm', validate})(FormWithError)

Solution 2: Use the global error prop

A second solution is to use the global error props, but you will have to display the errors from the container component using reduxForm.

Pay attention that this is a total antipatern ! Global error prop is for field independent errors.

import React from 'react'
import {reduxForm} from 'redux-form'

const renderInput = ({input, meta, ...props}) => (
    <input {...input} {...props} className={meta.error ? 'error' : null} />
)

const FormWithError = ({handleSubmit, error}) => (
    <div>
        <div className='errorContainer'>
            <span {...props} className='error'>Error : {error}</span>
        </div>
        <form onSubmit={handleSubmit}>
            <Field name='myInput' component={renderInput} />
        </form>
    </div>
)

const validate = (values, props) => {
    const errors = {}
    /* calculate errors here by appending theim to errors object */
    if(Object.keys(errors) > 0) {
        //You can concatenate each error in a string
        for(key in errors) errors._error += key + ': ' + errors[key]
        //or juste put the errors object in the global error property
        errors._error = {...errors}
    }
    return errors
}

export default reduxForm({form: 'myForm', validate})(FormWithError)

Solution 3: Get errors from the store

You always can get errors from the store by applying your validate function on the value presents in the store. It can be not performant for heavy validation because it run through validation at each render, so it runs twice when a value change and one for nothing if some other props changes. It can also be dificult to do with async validation.

import React from 'react'
import {reduxForm, formValueSelector} from 'redux-form'
import {connect} from 'redux'

const renderErrors = errors => {
    const errorNodes = []
    for(key in errors) errorNodes.push(<span className='error'>{key}: {errors[key]}</span>)
    return errorNodes
}

const renderInput = ({input, meta, ...props}) => (
    <input {...input} {...props} className={meta.error ? 'error' : null} />
)

let FormWithError = ({handleSubmit, values, ...otherProps}) => (
    <div>
        <div className='errorContainer'>
            {renderErrors(validate(values, otherProps))}
        </div>
        <form onSubmit={handleSubmit}>
            <Field name='myInput1' component={renderInput} />
            <Field name='myInput2' component={renderInput} />
        </form>
    </div>
)

const validate = (values, props) => {
    const errors = {}
    /* calculate errors here by appending theim to errors object */
    return errors
}

FormWithError = reduxForm({form: 'myForm', validate})(FormWithError)
FormWithError = connect(
    state => formValueSelector('myForm')(state, 'myInput1', 'myInput2')
)(FormWithError)

A last solution can be to store the errors in the store by implementing the componentWillReceiveProps and dispatching an action to update a list of error in the store but i don't think it's really a good idea. It's better to keep simple stateless component to render a Field component.

EDIT 26/12/2018 :

This last "solution" wasn't a good one at the time I've posted it. But since componentWillReceiveProps is deprecated in React, it's not a solution at all. Please don't do this in you application. I don't delete this for history in case this answer was linked somewhere.

这篇关于Redux-form:在页面顶部显示错误列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆