Why reducer ignores first item in the array?

懵懂的女人 提交于 2021-01-19 09:07:25

问题


I have this function that is supposed to run each validator and then return the object that contains errors.

Everything seems to work fine, but the first validator in the array. It seems like reduce completely ignores it. No matter what validator I put there, it just goes right over to the second one.

Am I missing something obvious here?

export default values => (
  [
    validateFullName,
    validateServicePresence,
    validatePhoneField,
    validateOrganizationName,
    validateInn,
    validateEmailField,
    validateManagerEmail,
    validateComment,
    validateAgreement,
  ].reduce((currentErrors, validator) => {
    const validationResult = validator(values);

    return {
      ...currentErrors,
      ...validationResult,
    };
  })
);

回答1:


If you don't provide an initial value to reduce, then it will use the first element of the array as the initial value, and skip calling your reducer with that element. So the very first time your reducer is called, currentErrors is validateFullName, and validator is validateServicePresence.

To fix this, just add an initial value:

export default values => (
  [
    validateFullName,
    validateServicePresence,
    validatePhoneField,
    validateOrganizationName,
    validateInn,
    validateEmailField,
    validateManagerEmail,
    validateComment,
    validateAgreement,
  ].reduce((currentErrors, validator) => {
    const validationResult = validator(values);

    return {
      ...currentErrors,
      ...validationResult,
    };
  }, {}) // <===================
);

See the initialValue section here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Parameters




回答2:


By default Array.prototype.reduce uses the first element as the accumulator value if no starting value is provided. Passing the statring value for the accumulator explicitly will make sure your first element is also processed.

See the initialValue parameter on the MDN docs

export default values => (
  [
    validateFullName,
    validateServicePresence,
    validatePhoneField,
    validateOrganizationName,
    validateInn,
    validateEmailField,
    validateManagerEmail,
    validateComment,
    validateAgreement,
  ].reduce((currentErrors, validator) => {
    const validationResult = validator(values);

    return {
      ...currentErrors,
      ...validationResult,
    };
  }, {})
); 


来源:https://stackoverflow.com/questions/57357537/why-reducer-ignores-first-item-in-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!