Redux-Form错误使用 Validation 导致 Max

2020-04-10  本文已影响0人  葱大驴

Code

我在 Redux-Form 种写了一个改密码的Form,其中用了2个校验方式

<Field
  name="password"
  label="New Password"
  component={CustomedComponent}
  validate={[Validatin.required]}
/> 
<Field
  name="rePassword"
  label="Re-confirm New Password"
  component={CustomedComponent}
  validate={[Validatin.required, Validation.changePwExpwMatch("password", 
    "New password is inconsistent")]}
/> 

第二个 Field 中,向 validation 中传入 changePwExpwMatch 这个方法, 这个方法定义在另外一个文件中,如下:

export const Validation = {
  changePwExpwMatch: (matchField, msg) => (value, allValues) => {
    return value !== allValues[matchField]
    ? msg
    : undefined
  }
}

用于校验两次输入的密码是否一致。

Error

在这个页面中,当用户重复输入第二个Field,会导致系统崩溃,浏览器的 console 里面显示

Maximum Update Depth Exceeded

根据网上网友提供的讨论,原因可能是 validation 传入方法会导致React 的重复渲染,导致 React 多层 Update.

Solution

把动态传入参数的校验方法预先定义,就不会触发 (validation !== validation),也就不会重复渲染。

const changePwExpwMatch =(matchField, msg) => (value, allValues) => {
    return value !== allValues[matchField]
    ? msg
    : undefined
  }
export const Validation = {
  validate: changePwExpwMatch('password', 'New password is inconsistent')
}
<Field
  name="password"
  label="New Password"
  component={CustomedComponent}
  validate={[Validatin.required]}
/> 
<Field
  name="rePassword"
  label="Re-confirm New Password"
  component={CustomedComponent}
  validate={[Validatin.required, Validation.validate]}
/> 

References

参考 stackoverflow 的讨论 :
Redux Forms sometimes ends up with register/unregister infinite loop
另外
React Redux Form Error Using Validation - Maximum Update Depth Exceeded

上一篇 下一篇

猜你喜欢

热点阅读