Redux: Using Spread Operator on 2D array

廉价感情. 提交于 2020-01-15 08:49:10

问题


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 ]   


来源:https://stackoverflow.com/questions/40393624/redux-using-spread-operator-on-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!