Alexander Riseley
Alexander Riseley

Reputation: 23

ReactJS - Can anyone explain how and why this state is being altered?

I am attempting to make Conway's Game of Life with React. I have an array of boolean values representing the grid in state, and then render an "alive" or "dead" cell for true or false values.

The solution I came up with for counting the surrounding number of "alive" neighbours to determine whether a cell is alive or dead in the next generation includes treating corner and edge cells separately from the rest of the middle cells.

In order to do this, I tried making a copy of the grid array and set the elements representing the corner and edge cells to null after counting their neighbours. Then, I was going to iterate over the remaining middle cells and count their surrounding neighbours.

However, after changing elements to null in the copy of the grid, the original grid in state is also changing. Can anyone explain this behaviour?

console.log(this.state.grid[topLeftCorner]); // false
innerSquare[topLeftCorner] = null;
console.log(this.state.grid[topLeftCorner]); // null

https://codepen.io/Egeroth/pen/jaeYwR

Upvotes: 2

Views: 79

Answers (2)

Bexultan Zhadyrassynov
Bexultan Zhadyrassynov

Reputation: 382

In the countNeighbours() method you are creating copy of the gird in a wrong way:

let innerSquare = this.state.grid;

This will copy only reference to the grid, not clone it.

You should write: let innerSquare = this.state.grid.slice(0); instead.

Adding .slice(0) will actually clone the grid into a new array.

Upvotes: 1

John
John

Reputation: 1341

When you assign a existing array to another variable, you do not get a copy, simply two variables which point to the same array. If you want to create a separate copy then consider using array.slice() and see Copying array by value in JavaScript for more details.

Upvotes: 4

Related Questions