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

React中如何用useState存储下拉选项的嵌套对象数据

解决React嵌套对象useState更新问题

问题根源

  • 原handleChange仅支持更新顶层属性,无法处理嵌套的id_type对象
  • 下拉组件写法错误:<option>的onChange和name属性无效,只有<select>的onChange会触发事件

解决方案

步骤1:修正下拉选择组件

去掉<option>上多余的属性,把code和name信息绑定到<option>的value和自定义data-*属性中:

<FormGroup>
  <Label for="id_type">Id type for customer</Label>
  <Input
    onChange={handleIdTypeChange}
    id="id_type"
    name="id_type"
    type="select"
    value={customer.id_type.code}
  >
    <option value="13" data-name="Citizenship card">Citizenship card</option>
    <option value="31" data-name="NIT">NIT</option>
  </Input>
</FormGroup>

步骤2:新增专门处理id_type的事件函数

因为id_type需要同时更新code和name两个字段,单独写一个处理函数更清晰:

const handleIdTypeChange = (e) => {
  const selectedCode = e.target.value;
  const selectedName = e.target.options[e.target.selectedIndex].dataset.name;
  
  setCustomer(prev => ({
    ...prev,
    id_type: {
      ...prev.id_type,
      code: selectedCode,
      name: selectedName
    }
  }));
}

可选:通用嵌套属性更新方案

如果需要让handleChange兼容所有字段(包括嵌套),可以修改函数支持解析属性路径(如id_type.code):

const handleChange = (e) => {
  const { name, value } = e.target;
  setCustomer(prev => {
    const path = name.split('.');
    const updated = { ...prev };
    let current = updated;
    
    for (let i = 0; i < path.length - 1; i++) {
      current[path[i]] = { ...current[path[i]] };
      current = current[path[i]];
    }
    current[path[path.length - 1]] = value;
    
    return updated;
  });
}

这种方式适合单独更新嵌套字段的场景,比如单独修改id_type.code或id_type.name,但无法同时更新两个字段,因此更推荐第一种专门处理的方案。

验证效果

选择"Citizenship card"时,customer对象会正确更新为:

{
  identification: "xxx-xxxx-xxxxx",
  id_type: {
    code: "13",
    name: "Citizenship card"
  },
  name: "xxxxxx",
  surname: "xxxxxxx"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:46:05