I
I
Incold2020-05-08 21:58:27
React
Incold, 2020-05-08 21:58:27

Why does an array change all its values?

Hello! I ran into a problem and I can't figure out what's going on. There is an array of gameHistory objects, each object has an array property, but when I add a new object to the array that has its own array, then each gameHistory[i].array becomes equal to gameState.array

Reducer:

const initialState = {
  moveInfo: [],
  gameHistory: []
};

export default function moveHistory(state=initialState, action) {

  switch (action.type) {
    case 'ADD_MOVE':
      return {
        ...state,
        moveInfo: [...state.moveInfo, action.move],
        gameHistory: [...state.gameHistory, action.gameState]
      }
      break;
       ...
   }
}


action:
export const addMove = (currentPlayer, location, gameState) => {
//console.log выводит правильно, т.е. приходит  gameState.array такой какой должен быть
  return ({
    type: 'ADD_MOVE',
    move: `Ходит "${currentPlayer}" на позицию [${location.map(item => item+1)}]`,
    gameState: gameState 
  })
}


The piece of code where this action is called:
let move = getState().game.moveCount;
let array = [...getState().game.squaresValue];
let currentPlayer = getState().game.currentPlayer;

array[num[0]][num[1]] = currentPlayer; // num приходит в аргументах
dispatch(addMove(currentPlayer, num, {array: array, // именно в этом свойстве проблема
currentPlayer: currentPlayer, moveCount: move}));

The result is that each intermediate console.log(array) tells me what I expect to see, but subscribe shows that the array property in each element of the gameHistory array becomes equal to the array property of the added gameState object.
How to fix it? Thanks for any help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
forspamonly2, 2020-05-09
@Incold

let array = [...getState().game.squaresValue];- here you make a copy of the outer array only. you have it two-dimensional, that is, the outer array of strings contains the inner arrays of cells.
as a result, the clone of the outer array contains links to the originals of the inner arrays and changes to them are visible in all copies.
replace with something like

let array = getState().game.squaresValue.map(row => [...row]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question