React Hook Form中useFormContext结合数组字段无法正常工作的问题求助
Answer:
This is a common gotcha with React Hook Form's context API—useFormContext doesn't accept configuration options like defaultValues. Those settings belong to the root useForm hook that creates the form context, not to the components consuming it via useFormContext.
Here's how to fix this step by step:
Move your
defaultValuesto the rootuseForminitialization
Wherever you're setting up theFormProvider(your top-level form component), define all your default values there:// Root component (e.g., App.js or FormWrapper.js) const methods = useForm({ mode: "onBlur", reValidateMode: "onChange", defaultValues: { secondName: "", items: DEFAULT_ITEMS // Include your array defaults here } }); return ( <FormProvider {...methods}> {/* Your tabs and shared button go here */} </FormProvider> );Simplify your
useFormContextcall
In yourUserDetails.jstab component, just retrieve the context methods without passing any config—all settings are inherited from the rootuseForm:// Tabs/UserDetails.js const { register, control, reset } = useFormContext(); const { fields, append, remove } = useFieldArray({ control, name: "items" });
Why this works:
The FormProvider passes down the fully configured form instance created by the root useForm. When you tried passing defaultValues to useFormContext, those values were ignored because the context consumer only accesses the existing form instance—it doesn't modify or reconfigure it.
By setting your defaults at the root, every component using useFormContext (including your tab components) will inherit those values, and useFieldArray will correctly render your initial array items.
If you need tab-specific default values, just structure your defaultValues object to match your form's field structure (e.g., userDetails: { secondName: "", items: DEFAULT_ITEMS } if your tab fields are nested under a namespace).
内容的提问来源于stack exchange,提问作者dev

