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

React Hook Form useFieldArray覆盖自定义id问题求助(v7.45.0+shadcn-ui)

解决方案

原因分析

react-hook-form 的 useFieldArray 默认以 id 作为数组项的唯一标识键:如果数组项未提供唯一的 id 值,它会自动生成随机 id 覆盖你定义的字段;即便你提供了 id,若值不唯一,它仍会生成内部标识保证数组项唯一性,导致自定义 id 被覆盖。

可行方案

1. 为新增项提供唯一自定义 id

确保调用 append 时传入的 id 是唯一值,让 useFieldArray 优先使用你定义的 id 而非自动生成。可借助 UUID 生成唯一值:

// 先安装 uuid 包:npm install uuid
import { v4 as uuidv4 } from 'uuid';

// 修改 append 逻辑
<Button onClick={() => append({ id: uuidv4(), test: [100] })}>Add List</Button>

2. 指定自定义内部标识键(避开默认的 id)

通过 useFieldArray 的 keyName 参数指定专门的内部标识字段,让它不再使用你的自定义 id 作为内部键:

const { fields, append, remove, update } = useFieldArray<{ id?: string, test?: number[], _key?: string }>({
  name: 'testArray',
  control: form.control,
  keyName: '_key' // 指定内部使用的标识键
});

// append 时传入唯一的 _key 值
<Button onClick={() => append({ id: '', _key: uuidv4(), test: [100] })}>Add List</Button>

3. 修正代码笔误

你的 update 方法写错了字段名,将 split 改为 test,否则无法正确更新 test 数组:

<Button onClick={() => update(index, { id: item.id, test: [...item.test, 0] })}>Add Number To Array</Button>

额外说明

官方文档提到的「新版本不会覆盖 id」,是指当你提供唯一且有效的 id 值时,useFieldArray 会优先使用你定义的 id;若 id 为空或重复,它依然会生成内部标识,导致自定义 id 被覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 21:44:56