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

ReactJS复选框对象数组取值异常:[Object object]问题修复

React复选框处理对象数组问题解决方法

问题核心是直接将对象作为复选框value时,会被自动转成[object Object]字符串,导致无法获取原对象结构。以下是具体修改方案:

方案一:直接传递对象(推荐)

1. 映射生成复选框

在onChange事件中直接传入当前产品对象,避免value属性的字符串化问题:

const products = [{food:'BREAD',price: 6}, {food:'MILK',price: 8}];
const [checked, setChecked] = useState([{ option: 'PRODUCTS',chosen: []}]);

{products.map((product) => (
  <div key={product.food}>
    <input
      type="checkbox"
      id={product.food}
      checked={checked[0].chosen.some(item => item.food === product.food)}
      onChange={() => handleChangeCheckbox(product)}
    />
    <label htmlFor={product.food}>{product.food} - ${product.price}</label>
  </div>
))}

2. 修改选中状态处理函数

基于最新状态,通过唯一标识(这里用food)判断产品是否已选中,完成添加/移除操作:

const handleChangeCheckbox = (selectedProduct) => {
  setChecked(prev => {
    const currentChosen = prev[0].chosen;
    const isSelected = currentChosen.some(item => item.food === selectedProduct.food);
    
    return [
      {
        ...prev[0],
        chosen: isSelected
          ? currentChosen.filter(item => item.food !== selectedProduct.food)
          : [...currentChosen, selectedProduct]
      }
    ];
  });
}

方案二:JSON序列化传递(适配需要使用value的场景)

如果必须通过value传递数据,可将对象序列化为JSON字符串,再在处理函数中解析:

1. 映射生成复选框

{products.map((product) => (
  <div key={product.food}>
    <input
      type="checkbox"
      id={product.food}
      value={JSON.stringify(product)}
      checked={checked[0].chosen.some(item => item.food === product.food)}
      onChange={(e) => handleChangeCheckbox(e.target.value)}
    />
    <label htmlFor={product.food}>{product.food} - ${product.price}</label>
  </div>
))}

2. 修改选中状态处理函数

const handleChangeCheckbox = (productStr) => {
  const selectedProduct = JSON.parse(productStr);
  setChecked(prev => {
    const currentChosen = prev[0].chosen;
    const isSelected = currentChosen.some(item => item.food === selectedProduct.food);
    
    return [
      {
        ...prev[0],
        chosen: isSelected
          ? currentChosen.filter(item => item.food !== selectedProduct.food)
          : [...currentChosen, selectedProduct]
      }
    ];
  });
}

两种方案都能保证chosen数组中存储完整的产品对象结构,方案一无需序列化操作,性能更优;方案二适合依赖value属性的场景(需注意对象不能包含循环引用)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:05:55