【问题标题】:Redux-form 6.0.0 access error outside Field component字段组件外的 Redux-form 6.0.0 访问错误
【发布时间】:2016-08-19 09:35:15
【问题描述】:

在 Redux-form v5 中,我能够从装饰表单中的任何位置访问“内联”错误(异步验证),如下所示:

const fields = [
  'email'
]

// inside the decorated form
const { email } = this.props.fields

console.log(email.error) // 'the validation error of the 'email' field

如何使用 Redux-form 6.0.0+ 实现相同的目标?

【问题讨论】:

    标签: reactjs redux-form


    【解决方案1】:

    如果您想在输入旁边显示错误,则应在传递给Fieldcomponent 中处理它。如果您想一起显示所有错误,例如在表单底部的提交按钮,您可以使用新的Fields component,如下所示:

    const fieldNames = [
      'email',
      'password'
    ]
    
    const renderAllErrors = fields => (
      <ul>
        {Object.keys(fields).map(key => {
          const { meta: { touched, error } } = fields[ key ]
          return touched && error ? <li key={key}>{key}: {error}</li> : undefined
        })}
      </ul>
    )
    
    ...
    
    <Fields names={fieldNames} component={renderAllErrors}/>
    

    【讨论】:

    • 当我遍历字段时,其中一个道具是名称数组。通过阅读文档(redux-form.com/6.0.2/docs/api/Fields.md/#props),我认为它不会被添加为道具。当我运行上面的代码时,我得到 - Uncaught (in promise) TypeError: Cannot read property 'touched' of undefined(...)
    • 仅供未来使用此功能的任何人参考。如果您想有条件地显示错误列表,请记住在您的 renderAllErrors 方法中进行检查。将Fields 包装在自定义组件中并在那里进行检查可能会导致Fields-组件卸载并注销所有fieldNames
    • @DomHede 我也有同样的经历。 fields 还包含 Forms 的 names 属性。您可以通过{Object.keys(fields).filter(x =&gt; x.name =! "names").map(key ...进行过滤
    【解决方案2】:

    我找到的解决方案是使用error prop (http://redux-form.com/6.0.0-rc.4/docs/api/Props.md/#-error-any-)。 从我的asyncValidate 函数中,我用我的字段错误填充返回的error._error 对象。然后我可以使用装饰的表单访问它 const { error } = this.props.

    如果有人有更好的解决方案...

    编辑:不要这样做。使用有效答案(Fields 组件)。

    【讨论】:

    • 嗨,Erik,实际上我对该解决方案不满意,因为我不知道表单字段是否为 touched。因此它显示每个字段的每个错误。仍在寻找复制 v5 行为的正确方法。 (顺便说一句,感谢您在这个项目上所做的出色工作)。
    • 访问syncErrors对象怎么样?
    猜你喜欢
    • 2019-01-14
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    相关资源
    最近更新 更多