React中useForm发送HTTP PATCH请求:实现数组元素单操作
解决React useForm中PATCH数组生成独立replace操作的问题
要实现为数组每个元素生成独立的replace操作,核心是生成符合JSON Patch规范的操作数组,而非把整个数组作为单个操作的value。
具体实现步骤
- 从useForm的表单数据中取出
participants数组 - 遍历数组,为每个元素生成独立的Patch操作对象
- 将生成的操作数组直接作为PATCH请求的Body发送
代码示例
import { useForm } from 'react-hook-form'; function ParticipantForm() { const { register, handleSubmit, watch, setValue } = useForm({ defaultValues: { participants: [{ name: '', email: '' }] // 默认初始值 } }); // 实时监听participants数据,用于动态渲染输入框 const participants = watch('participants'); const onSubmit = async (formData) => { // 生成JSON Patch操作数组 const patchOps = formData.participants.map((item, idx) => ({ op: 'replace', path: `/participants/${idx}`, value: item })); // 发送PATCH请求 try { const res = await fetch('/api/your-target-endpoint', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patchOps) }); if (!res.ok) throw new Error('请求失败'); const result = await res.json(); console.log('更新完成:', result); } catch (err) { console.error('更新出错:', err); } }; // 动态添加参与者输入框的逻辑 const addParticipant = () => { setValue('participants', [...participants, { name: '', email: '' }]); }; return ( <form onSubmit={handleSubmit(onSubmit)}> {participants.map((_, idx) => ( <div key={idx} className="participant-input-group"> <input {...register(`participants.${idx}.name`, { required: true })} placeholder="参与者姓名" /> <input {...register(`participants.${idx}.email`, { required: true })} placeholder="参与者邮箱" /> </div> ))} <button type="button" onClick={addParticipant}>添加参与者</button> <button type="submit">提交更新</button> </form> ); }
关键注意点
- 不要把操作数组嵌套在其他对象里(比如
{ operations: patchOps }),后端需要直接接收操作数组格式的Body - 如果是新增数组元素而非替换已有元素,可将
op改为add,path设为/participants/-(JSON Patch规范中-表示追加到数组末尾) - 确保后端接口支持JSON Patch协议,能正确解析每个操作并执行对应更新
内容的提问来源于stack exchange,提问作者Jakub Skorus
相关产品推荐
相关产品推荐

