Redux:在2D阵列上使用Spread Operator

时间:2016-11-03 03:57:06

标签: javascript arrays reactjs redux spread-syntax

React.js的新手,我很难在我的reducers中使用spread运算符来更新具有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。

1 个答案:

答案 0 :(得分:1)

因为旧值被赋值为null

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

然后你试图读取null的第零索引,这将抛出错误。

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

<强>更新

grid是一个数组,但是你要返回对象..更改为下面的语法

grid: [ ...state.grid, state.grid[oldCoords[0]][oldCoords[1]]=1 ]