【发布时间】:2017-03-16 13:44:50
【问题描述】:
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。
【问题讨论】:
标签: javascript arrays reactjs redux spread-syntax