React Hook Form useFieldArray 过滤已选项后 remove() 异常
数据小陈
结论
remove(index) 不会主动清空其他行的 select。常见原因是 select 的 options 由 useWatch 动态过滤,而 select 本身并没有做成受控组件:执行 remove(index) 后字段数组会重排,useWatch 的更新和 DOM 渲染之间存在时序差,当前行已选中的 article 可能短时间不在 options 里,浏览器就会把 select 显示成空值。看起来就像“删掉最后一行时,把其他 select 一起清空了”。
原因拆解
remove(index)会让后续行的索引前移,register('dettaglio_articoli.${index}.articolo.id')的字段名也会跟着变化。- 过滤 options 时,如果用
dettaglioArticoliWatch和当前index比较,watch 值可能晚一帧更新。 - 原生
select的显示值取决于当前 option 是否存在。当前选中的 id 一旦被过滤掉,浏览器就会显示第一个 option 或空值。 fields.map的 key 继续用item.id,不要换成index。
修复步骤
- 用
Controller接管 select 的值,交给 react-hook-form 管理。 - 过滤 options 时排除其他行已选的 id,但当前行自己的 id 要保留。
remove(index)只删除字段,不要再手动清空其他行。- 如果
article.id是数字,onChange里用Number转换;空值用null或undefined。
代码示例
import { Controller, useFormContext, useWatch, useFieldArray } from 'react-hook-form';
// 组件内部
const { control, formState: { errors } } = useFormContext();
const { fields, append, remove } = useFieldArray({ control, name: 'dettaglio_articoli' });
const watched = useWatch({ control, name: 'dettaglio_articoli' }) ?? [];
return (
<>
{fields.map((item, index) => {
const currentId = watched[index]?.articolo?.id;
const otherSelectedIds = new Set(
watched
.map((row, i) => (i !== index ? row?.articolo?.id : null))
.filter((id) => id !== null && id !== undefined)
);
const options = articoliDisponibili.filter(
(articolo) => articolo.id === currentId || !otherSelectedIds.has(articolo.id)
);
return (
<div key={item.id}>
<Controller
control={control}
name={`dettaglio_articoli.${index}.articolo.id`}
render={({ field }) => (
<select
value={field.value ?? ''}
onChange={(e) =>
field.onChange(e.target.value === '' ? null : Number(e.target.value))
}
>
<option value=''>---------</option>
{options.map((articolo) => (
<option key={articolo.id} value={articolo.id}>
{articolo.nome}
</option>
))}
</select>
)}
/>
<button type='button' onClick={() => remove(index)}>
删除
</button>
</div>
);
})}
</>
);
注意事项
Number(e.target.value)只在article.id是数字时成立。id 是字符串就保留原值,不要转数字。- 如果仍用
register而不用Controller,过滤 options 时至少要保留当前行已选值,并且不要在remove后再手动setValue清空其他行。 - 继续用
fields返回的item.id作为 key,不要用index。 - 如果还会短暂闪烁,可以在
remove后调用trigger('dettaglio_articoli')做一次校验,但不要拿它代替受控值。
备注:内容仅供参考。
