Redux: Using Spread Operator on 2D array

2019-08-02 09:05发布

问题:

New to React.js, I am having hard time using the spread operator in my reducers to update my state that has an 2D-array property.

For instance initial state is so:

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

After binding the action, lets say the payload goes to 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 }
    }
  }
}

I am able to update the player's state, but not the grid. Essentially I want to update the coordinates from oldCoords and assign it to 1.

回答1:

its because the old value is assigned to null

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

and then you are trying to read zeroth index of null, that will throw the error.

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

Update:

grid is an array but you are returning the object ..change to below syntax

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