You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Move your defaultValues to the root useForm initialization
    Wherever you're setting up the FormProvider (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>
    );
    
  2. Simplify your useFormContext call
    In your UserDetails.js tab component, just retrieve the context methods without passing any config—all settings are inherited from the root useForm:

    // 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 10:07:35