The state is updated before the call to setState

lifeParser

is a method called to process and update boardData. The problem is that boardData is being updated while the loop is still processing.

lifeParser(){
    var parseArray = this.state.boardData.slice(0);

    for(var i=0;i<30;i++){
        for(var j=0;j<30;j++){
            parseArray[i][j] = 5; // boardData gets updated here before setState is even called
        }
    }
    this.setState({boardData : parseArray});
}

      

+3


source to share


2 answers


This is because yours boardData

is multidimensional and you cannot clone it with just a method slice

. Use it with the map

following.

var parseArray = this.state.boardData.map(function(arr) {
    return arr.slice();
});

      



or with arrow syntax

var parseArray = this.state.boardData.map(a => a.slice());

      

+2


source


Because it is a nested array. You only copy the first level (shallow clone). Internal arrays are all the same references. Consider the following example:

var nestedArray = [
 [1, 2, 3],
 [6, 6, 6, 6, 7, 8],
 [0, 3, 5, 6, 5]
];

// This only does a shallow clone
var copy = nestedArray.slice(0);

// When you do this
copy[0][0] = 100;

// `nestedArray` will also be mutated,
// you get 100 here
console.log(nestedArray[0][0]);

      

In your case, you can do a deep clone, or just use something like this map()

to get a fresh new array:

lifeParser(){
    var parseArray = this.state.boardData.slice(0);

    for (var i = 0; i < 30; i++) {
      parseArray[i] = parseArray[i].map(() => 5);
    }
    this.setState({boardData : parseArray});
}

      



The deep clone is more expensive in this example because you need 1 more loop. The advantage of using it map()

is that you compute and clone your data at the same time.

You can also use two map()

in this example:

lifeParser(){
    var parseArray = this.state.boardData.map(innerArray => innerArray.map(() => 5));
    this.setState({boardData : parseArray});
}

// Or this might be more readable:
var parseArray = this.state.boardData.map(innerArray => {
  return innerArray.map(() => 5);
});

      

+2


source







All Articles