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

React中如何通过变量键正确更新state对象?

问题分析与解决

错误原因

你代码里的核心问题是对currentPlayer的使用错误:currentPlayer是存储玩家编号的数字(1或2),根本不是包含row和column的对象,所以currentPlayer.row、currentPlayer.column这两个表达式的结果都是undefined。这就导致你更新playerLocation时,往对象里塞了两个键为undefined的属性,完全没修改到对应玩家的位置。

正确的状态更新方式

要修改当前玩家的位置,应该以currentPlayer(玩家编号)作为键,重新构造该玩家的位置对象,同时用扩展运算符保留其他玩家的原有数据:

const movePlayer = (location) => {
  setPlayerLocation({
    ...playerLocation,
    // 用当前玩家编号作为键,覆盖其位置对象
    [currentPlayer]: {
      row: location.row,
      column: location.column
    }
  });
}

如果担心React状态异步更新导致的旧值引用问题,更稳妥的写法是用函数式更新(当新状态依赖旧状态时推荐):

const movePlayer = (location) => {
  setPlayerLocation(prevPlayerLocation => ({
    ...prevPlayerLocation,
    [currentPlayer]: {
      row: location.row,
      column: location.column
    }
  }));
}

这样就能精准修改对应玩家的位置,不会再出现undefined键的异常情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:05:34