【问题标题】:Redux: Using Spread Operator on 2D arrayRedux:在二维数组上使用扩展运算符
【发布时间】: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


    【解决方案1】:

    因为旧值被赋值为 null

    让初始状态 = { 网格:新数组(5).fill(新数组(5).fill(0)), 玩家:{ 坐标:空, 健康:100 } }

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

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

    更新:

    grid 是一个数组,但您将对象 ..change 返回到以下语法

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

    【讨论】:

    • 抱歉,我忘记编辑我的帖子,其中发送操作时 player.coords 已经初始化。
    猜你喜欢
    • 2017-03-17
    • 2016-06-12
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 2019-03-13
    • 2020-05-09
    • 2021-05-10
    相关资源
    最近更新 更多