Answer the question
In order to leave comments, you need to log in
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;
...
}
}
export const addMove = (currentPlayer, location, gameState) => {
//console.log выводит правильно, т.е. приходит gameState.array такой какой должен быть
return ({
type: 'ADD_MOVE',
move: `Ходит "${currentPlayer}" на позицию [${location.map(item => item+1)}]`,
gameState: gameState
})
}
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}));
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question