问题
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