I am running into really, really weird behavior with Redux. Basically I have a game with a static map where the player moves around on the map. The map and the player is represented by colored div
's. That's all I'm trying to do and I was briefly able to get it working.
I create the movement by first getting the empty map (which is a hardcoded const
array of arrays) and then adding the player's (new) position at the correct coordinates. Then I render it to the view layer in React. The outputted new map with the player's position is not named the same as the empty map.
However something very weird is happening with Redux where it is somehow changing the hardcoded const
array of arrays when I render it. Putting in a ton of console.logs to see what is going on with the variables confirm that this is what is happening. Could someone please have a look at this codepen:
http://codepen.io/swyx/pen/MJbezj?editors=1010
and teach me how to trace what on earth is going on with my mutable const?
EDIT: here is the relevant code (constMap is a const array of arrays)
const InitMap = function() {
console.log('InitMap')
return constMap /// why is this changing every single time???
}
this is later combined with the other reducers:
const rootReducer = combineReducers({
gamemap: InitMap,
user: InitUser,
userMove: UserMove
});
and then used in the relevant mapStateToProps function:
function GMmapStateToProps(state){
//from here goes into this.props
console.log('GMmapStateToProps')
console.log(state)
console.log(constMap)
var newgamemap = constMap, //state.gamemap also doesnt work,
newuser = state.user
console.log(newgamemap)
if (state.userMove) {
//check if is whitespace
var x2 = newuser.location.x + state.userMove.vector.x
var y2 = newuser.location.y + state.userMove.vector.y
if (newgamemap[y2][x2] === 1) {
newuser.location.x = x2
newuser.location.y = y2
//add user
newgamemap[newuser.location.y][newuser.location.x] = 9
}
} else {
//add user
newgamemap[newuser.location.y][newuser.location.x] = 9
}
console.log(newgamemap)
return{
xgamemap: newgamemap,
user: newuser
}
}
what is ridiculous is the value of constMap
keeps changing every time i call this! why/how? it is making me question my sanity.