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

React Hooks嵌套对象设置问题:票务分类联动下拉框异常

解决方案

咱们先定位核心问题:你的handleCategory函数现在直接把category里的顶层键(比如9871)替换成了字符串值,完全忽略了原本的嵌套结构;同时渲染下拉框时,value的取值也没指向嵌套对象里的具体项,这才导致结构变平、联动失效。接下来一步步修正:

1. 先修正createCategory的笔误

你代码里的cat2是未定义的变量,应该改成nestedCat,不然会直接报错:

const createCategory = () => {
  let cat = {}
  let nestedCat = {}
  for (let it in item) {
    for (let bt in item[it].buyertypes) {
      // 把cat2修正为nestedCat
      nestedCat[item[it].buyertypes[bt].id] = ''
    }
    cat[item[it].id] = nestedCat
    nestedCat = {}
  }
  return cat
}

2. 重写handleCategory实现联动逻辑

现在要做的是:选中某个分类后,找到对应的catId,把该catId下所有嵌套的子项值都同步为选中值,同时保留原对象结构:

const handleCategory = e => {
  const { name: catId, value: selectedValue } = e.target;
  // 深拷贝原category对象,避免直接修改state
  const updatedCategory = JSON.parse(JSON.stringify(category));
  // 遍历当前catId下的所有子项,统一设置为选中值
  for (const qntId in updatedCategory[catId]) {
    updatedCategory[catId][qntId] = selectedValue;
  }
  setCategory(updatedCategory);
}

3. 修正分类下拉框的value绑定

原来的value={category[i.catId]}取值错误,应该绑定到嵌套对象里的具体项,这样每个下拉框才能正确显示对应的值:

<select 
  value={category[i.catId][i.qntId]} 
  onChange={handleCategory} 
  name={i.catId}
>
  <option value="">Choose</option>
  {categories.map((cat, index) => (
    <option key={index} value={cat.id}>
      {cat.description} {cat.value}
    </option>
  ))}
</select>

验证效果

现在操作下拉框时,同组(同一个catId)的所有分类下拉框会同步选中值,category对象也会保持你期望的嵌套结构:

{
  9871: { 1: "11", 2: "11", 3: "11" },
  9872: { 5: "7", 6: "7", 8: "7" }
}

而且每个下拉框的name属性依然保留为i.catId,完全满足表单验证的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 20:57:39