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

React useState对象更新:使用变量作为键名失效问题排查

问题:React useState更新对象时错误新增键而非替换目标值

我编写了一个用于更新React useState对象的函数,期望根据inputIndex(取值为1-4的数字)替换对象中对应键的值,但实际执行后,对象中新增了名为inputIndex的键而非替换目标键的值。请问我哪里出错了?

原代码:

const [selected, setSelected] = useState({
  1:"80/static\\images\\00205.png",
  2:"80/static\\images\\00206.png",
  3:"80/static\\images\\00207.png",
  4:"80/static\\images\\00210.png"
});
const set = (inputIndex) =>{
  setSelected({...selected, inputIndex:"80/static\\images\\0001.png"})
} 

调用set后的输出:

{1: '80/static\\images\\00205.png', 2: '80/static\\images\\00206.png', 3: '80/static\\images\\00207.png', 4: '80/static\\images\\00210.png', inputIndex: 'http://85.229.133.157:80/static\\images\\00210.png'}

解答

问题出在对象字面量的键名写法上:

  • 直接写inputIndex时,JS会把它当作固定字符串键名,所以会新增一个叫inputIndex的键,而不是用变量inputIndex的实际值作为键名。
  • 要让变量的值作为键名,必须用方括号语法包裹变量,这样JS会解析变量的实际值作为键。

修改后的set函数:

const set = (inputIndex) =>{
  setSelected({...selected, [inputIndex]:"80/static\\images\\0001.png"})
} 

这样调用时,[inputIndex]会计算出变量的实际值(比如1、2、3、4),用这个值作为键名去覆盖原对象中对应位置的值,就不会新增多余的键了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:55:31