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

如何使用react-hook-form渲染含全零数组的表单?

问题:react-hook-form数组含零值时输入框不渲染

我用react-hook-form实现了嵌套数组表单,当数组元素全为0时,对应的输入框完全不显示;但数组包含非零值(比如[0,1,2])时,输入框能正常渲染。

复现代码

import "./styles.css";
import { useForm, useFieldArray, Control, Controller } from 'react-hook-form';
import { useState } from 'react';

const defaultValues = {
  "foo": [
    {
      "bar": [0, 0, 0]
    },
    {
      "bar": [4, 5, 6]
    }
  ]
}


const FooComponent = ({fooIndex, control}) => {
  const { fields, append, remove } = useFieldArray({
    control,
    name: `foo.${fooIndex}.bar`,
    keyName: 'id'
  });

  return (
    <div>
      <h1>Foo</h1>
      {fields.map((field, index) => (
        <Controller
          key={field.id}
          name={`foo.${fooIndex}.bar.${index}`}
          control={control}
          defaultValue={String(field.value)} // Convert to string
          render={({field}) => (
            <input {...field} value={String(field.value)} /> // Ensure the value is a string
          )}
        />
      ))}
    </div>
  )
};


export default function App() {
  const { control, handleSubmit, getValues } = useForm({
    defaultValues
  });
  const [formValue, setFormValue] = useState(null);

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'foo',
    keyName: 'id'
  });

  const onSubmit = async () => {

  };

  const handlePrintForm = () => {
    setFormValue(getValues())
  };

  return (
    <div className="App">
      <div>
        <h1>Form value:</h1>
        <p>{JSON.stringify(formValue, null, 2)}</p>
      </div>
      <form onSubmit={handleSubmit(onSubmit)}>
        {fields.map((field, index) => (
          <div key={field.id}>
            <FooComponent fooIndex={index} control={control}/>
          </div>
        ))}
        <button onClick={(()=>append({'bar': [1, 2, 3]}))}>Add Foo</button>
      </form>
      <button onClick={handlePrintForm}>Print form</button>
    </div>
  );
}

现象说明

  • 当bar数组为[0,0,0]时,无输入框渲染
  • 当bar数组为[0,1,2]时,3个输入框正常显示

修复方案

问题根源是useFieldArray默认会过滤假值(falsy values),0属于假值,因此全零数组会被当作空数组处理,导致无字段生成。

只需给FooComponent中的useFieldArray添加shouldUnregister: false配置,关闭自动注销假值的行为:

const { fields, append, remove } = useFieldArray({
  control,
  name: `foo.${fooIndex}.bar`,
  keyName: 'id',
  shouldUnregister: false // 新增配置
});

该配置的作用是:即使字段值为0这类假值,react-hook-form也会保留对应的字段,不会自动注销,输入框就能正常渲染。

内容的提问来源于stack exchange,提问作者Tom McLean

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 02:19:56