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

React中如何通过表单输入更新嵌套对象的状态值

问题解决方法

首先要注意两个核心问题:

  • 你的patientUpdate是数组类型,但当前handleChangeEvent里把它当成对象展开,直接破坏了原有的数组结构。
  • 要更新嵌套在patientInfo里的属性,必须逐层展开对象,不能直接在外层新增字段。

针对当前单一患者数据的修正代码

假设你表单输入框的name属性就是patientInfo里的字段名(比如name="name"、name="email"),可以这样修改事件处理函数:

function handleChangeEvent(event) {
  const { name, value, type, checked } = event.target;
  const inputValue = type === "checkbox" ? checked : value;

  setPatientUpdate((prevPatientUpdate) => {
    // 取出数组里的唯一患者对象,逐层展开并更新目标属性
    const updatedPatient = {
      ...prevPatientUpdate[0],
      patientInfo: {
        ...prevPatientUpdate[0].patientInfo,
        [name]: inputValue
      }
    };
    // 返回新的数组
    return [updatedPatient];
  });
}

适配多患者数据的扩展方案

如果后续你的state里会有多个患者对象,可以通过id定位要修改的对象,代码调整如下:

// 表单元素需添加data-id属性绑定患者id,比如<input data-id="1" name="name" />
function handleChangeEvent(event) {
  const { name, value, type, checked, dataset } = event.target;
  const targetPatientId = parseInt(dataset.id);
  const inputValue = type === "checkbox" ? checked : value;

  setPatientUpdate((prevPatientUpdate) => {
    return prevPatientUpdate.map(patient => {
      if (patient.id === targetPatientId) {
        return {
          ...patient,
          patientInfo: {
            ...patient.patientInfo,
            [name]: inputValue
          }
        };
      }
      return patient;
    });
  });
}

额外语法提醒

你当前的state定义里id: ,存在语法错误,记得给它赋值(比如id: 1)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:18:13