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

如何在React中更新state条目并在更新前将其内容回显到输入框

实现方案

核心逻辑通过数组索引定位条目,规避name重复导致查找失败的问题,配合react-hook-form的表单能力实现需求,具体实现如下:

  • 新增editingIndex状态存储当前编辑条目的索引,初始值为-1(代表当前无编辑条目)
  • 点击行内编辑按钮时,将当前条目的索引赋值给editingIndex,同时调用react-hook-form提供的setValue方法将对应条目数据回填到表单输入框
  • 提交表单时判断editingIndex值:
    • 等于-1时走新增逻辑,将表单数据追加到用户数组末尾
    • 不等于-1时走更新逻辑,替换数组中对应索引位置的条目数据,完成后重置editingIndex为-1并清空表单
  • 删除功能同理,直接通过索引过滤数组即可

完整代码示例如下:

import { useForm } from 'react-hook-form';
import { useState } from 'react';

export default function UserForm() {
  const { register, handleSubmit, setValue, reset } = useForm();
  // 存储用户列表
  const [userList, setUserList] = useState([]);
  // 存储当前编辑的条目索引,-1代表未编辑
  const [editingIndex, setEditingIndex] = useState(-1);

  // 编辑按钮点击事件
  const handleEdit = (index) => {
    const targetUser = userList[index];
    // 回填表单数据
    setValue('name', targetUser.name);
    setValue('age', targetUser.age);
    // 记录当前编辑的索引
    setEditingIndex(index);
  };

  // 表单提交逻辑
  const onSubmit = (data) => {
    if (editingIndex === -1) {
      // 新增逻辑
      setUserList([...userList, data]);
    } else {
      // 更新逻辑:通过索引替换对应条目
      const newList = [...userList];
      newList[editingIndex] = data;
      setUserList(newList);
      // 重置编辑状态
      setEditingIndex(-1);
    }
    // 清空表单
    reset();
  };

  // 删除逻辑
  const handleDelete = (index) => {
    setUserList(userList.filter((_, i) => i !== index));
    // 如果删除的是正在编辑的条目,重置编辑状态
    if (editingIndex === index) {
      setEditingIndex(-1);
      reset();
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <input {...register('name', { required: true })} placeholder="用户名" />
        <input {...register('age', { required: true })} placeholder="年龄" />
        <button type="submit">
          {editingIndex === -1 ? '新增' : '更新'}
        </button>
      </form>
      {/* 用户列表渲染 */}
      <div>
        {userList.map((user, index) => (
          <div key={index} style={{ display: 'flex', gap: '20px', margin: '10px 0' }}>
            <span>姓名:{user.name}</span>
            <span>年龄:{user.age}</span>
            <button onClick={() => handleEdit(index)}>编辑</button>
            <button onClick={() => handleDelete(index)}>删除</button>
          </div>
        ))}
      </div>
    </div>
  );
}

如果你的业务场景存在列表排序、筛选等操作,使用数组索引作为key会存在稳定性问题,可以在新增条目时给每个用户对象追加唯一标识,比如id: Date.now(),后续通过id定位条目即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:15:00