Been banging my head on this one for a while now. I’m trying to build a simple React game with Merge-3 mechanics. It’s a 5x5 grid, and I’ve set up my state like this:
this.state = {
boardState: [
[1,0,0,0,0],
[2,0,0,0,0],
[3,0,0,0,0],
[4,0,0,0,0],
[5,0,0,0,0]
]
}
I’m not 100% sure that a nested array is the best way to handle this data, but I’m gonna stick with it for the time being.
Anyway, now the handleClick function:
handleClick (event) {
const rowindex = parseInt(event.target.getAttribute('rowindex'));
const tileindex = parseInt(event.target.getAttribute('tileindex'));
const tileText = this.state.boardState[rowindex][tileindex];
console.log('tile value: ', tileText);
this.setState(state => {
const row = state.boardState.map((row, i) => {
let tile;
if (i === rowindex) {
tile = row.map((cell, j) => {
if (j === tileindex && tileText === 0) {
return cell + 1;
} else { return cell; }
});
return tile;
} else { return row; }
});
return {
row,
};
});
};
It almost works, but it isn’t actually updating the state and I’m not sure why. When I was testing it with a simple array, it worked perfectly. I have fiddled with values, trying to return different things, but I can’t get it working.
I’m sure I’m missing something obvious, but any help would be appreciated.