1

React.js 的新手,我很难在减速器中使用扩展运算符来更新具有 2D 数组属性的状态。

例如初始状态是这样的:

let initialState = {
    grid: new Array(5).fill(new Array(5).fill(0)),
    player: { coords: [2,3], health: 100 }
}

绑定动作后,假设有效负载进入PRESS_LEFT

case PRESS_LEFT: {
  let oldCoords = [state.player.coords[0], state.player.coords[1]];
  let newCoords = [state.player.coords[0], state.player.coords[1]-1];
  let thereIsWall = validateWall(state.grid, newCoords);
  if (thereIsWall){
    return state
  } else{
    return{
      ...state,
      player: { ...state.player, coords: newCoords },
      grid: { ...state.grid, state.grid[oldCoords[0]][oldCoords[1]] = 1 }
    }
  }
}

我能够更新玩家的状态,但不能更新网格。本质上我想更新坐标oldCoords并将其分配给1。

4

1 回答 1

1

这是因为旧值被分配给 null

让 initialState = { grid: new Array(5).fill(new Array(5).fill(0)), player: { coords: null, health: 100 } }

然后您尝试读取 null 的第零个索引,这将引发错误。

let oldCoords = [state.player.coords[0], state.player.coords[1]];

更新:

grid 是一个数组,但您将对象 ..change 返回到以下语法

grid: [ ...state.grid, state.grid[oldCoords[0]][oldCoords[1]]=1 ]   
于 2016-11-03T04:03:15.520 回答