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

React中使用变量作为对象键名更新状态时被识别为字符串的问题排查与解决

问题分析与修复方案

嘿,这个坑我之前也踩过!你遇到的是JavaScript对象字面量的一个常见特性——常规写法下,对象的键会被当作字符串字面量处理,而不是解析变量的实际值。

问题根源

你写的targetedProductId: targetedProductQuantity里,targetedProductId会被直接当成固定字符串键名,而不是取变量targetedProductId的值(也就是你期望的e.target.id)。这就是为什么最终状态里的键总是"targetedProductId",而非实际的产品ID。

修复方案

要让变量的值作为对象的键,你需要用JavaScript的计算属性名(Computed Property Names)语法——把变量用方括号[]包裹起来,这样JavaScript就会先求值变量,再把结果作为键名。

修复后的handleQuantity函数如下:

const handleQuantity=(e)=>{ 
  const targetedProductId=e.target.id 
  const targetedProductQuantity=e.target.value 
  setOrderProductQuantity({ 
    ...orderProductQuantity, 
    [targetedProductId]: targetedProductQuantity // 用方括号包裹变量,使其作为动态键
  }) 
}

额外优化建议

如果你的状态更新依赖于之前的状态(比如这种对象合并的场景),更稳妥的方式是使用函数式更新,这样可以确保你拿到的是最新的状态值,避免闭包导致的旧状态残留问题:

const handleQuantity=(e)=>{ 
  const targetedProductId=e.target.id 
  const targetedProductQuantity=e.target.value 
  setOrderProductQuantity(prevState => ({ 
    ...prevState, 
    [targetedProductId]: targetedProductQuantity 
  })) 
}

这种写法会基于最新的prevState来合并更新,在频繁触发状态变更的场景下更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 20:08:10