在2D阵列上使用扩展运算符

在2D阵列上使用扩展运算符

本文介绍了Redux:在2D阵列上使用扩展运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React.js的新手,我很难在我的化简器中使用散布运算符来更新具有2D数组属性的状态.

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.

例如初始状态为:

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

绑定动作后,可以说有效负载转到 PRESS_LEFT

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 }
    }
  }
}

我能够更新玩家的状态,但不能更新网格.本质上,我想从oldCoords更新坐标并将其分配给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.

推荐答案

它是因为旧值被分配为null

its because the old value is assigned to null

let initialState = { 网格:new Array(5).fill(new Array(5).fill(0)), 玩家:{ coords:null,健康度:100}}

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

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

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]];

更新:

grid是一个数组,但是您正在将对象..change更改为以下语法

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

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

这篇关于Redux:在2D阵列上使用扩展运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:02