为何redux-form源码中createField.js的函数需嵌套包裹?
validate/warn in redux-form's register Method Great question—this is all about ensuring the form always uses the latest validation and warning logic tied to your Field component's props, even as those props change over time. Let's break down the reasoning:
1. Avoid Stale Function References
If we passed nextProps.validate directly instead of wrapping it in a function, redux-form would store a fixed reference to the validation function that existed at the time register was called.
Imagine your parent component dynamically updates the validate prop (e.g., based on user input or state changes). If redux-form held onto the old function reference, it would continue using outdated validation logic even after the Field's props had updated.
By wrapping it in () => nextProps.validate, we're giving redux-form a way to fetch the latest version of the function every time it needs to run validation. When redux-form invokes this nested function during a validation cycle, it will pull the current validate prop from the Field component's latest props, not the one that existed when register was first called.
2. Handle Dynamic Prop Updates Gracefully
redux-form's register method is typically called in lifecycle hooks like componentWillReceiveProps (as seen in your code snippet), but relying solely on re-registering on prop changes isn't foolproof. There might be edge cases where a prop updates but register isn't triggered immediately, or where redux-form's internal caching optimizations skip re-registration.
The nested function acts as a safety net: no matter when validation runs, it will always use the most up-to-date validation/warning function from the Field's current props. This guarantees consistency between your component's props and the validation logic redux-form executes.
3. Align with redux-form's Internal Design
Under the hood, redux-form stores these "getter" functions rather than the validation functions themselves. This design fits with how redux-form manages form state and validation cycles—when it needs to validate a field, it iterates through the registered fields and invokes these getter functions to retrieve the current validation rules, ensuring everything stays in sync with your component tree's latest state.
内容的提问来源于stack exchange,提问作者Stuart Bourhill

