除了未设置的布尔变量外,我还有Redux reducer。代码:
const GameBoardReducer = function(state, action) {
if( state === undefined ) {
let state = {
rows: BOARD_ROWS,
cols: BOARD_COLS,
width: Math.min( document.body.clientWidth * 0.9, 1184 ),
board: [],
running: false,
framesPerSec: 5,
}
for( var i=0 ; i<BOARD_ROWS ; i++ ) {
state.board.push([]);
for( var j=0 ; j<BOARD_COLS ; j++ ) {
state.board[i].push(Math.random()<0.15? FIELD_ALIVE: FIELD_DEAD);
}
}
return state;
}
switch(action.type) {
case SET_BOARD_ACTION:
return { ...state, board: action.payload };
case RUN_ACTION:
console.log("RunAction:", action.payload);
return { ...state, running: action.payload };
}
return state;
}
控制台显示
RunAction:true
但容器中的值:this.props.gameBoard.running
仍为假。
为什么?
答案 0 :(得分:1)
在你的笔中,你在setInterval
中持有对游戏板的引用并检查它是否正在运行,而不是在this.props中检查游戏板。尝试这些更改:
this.state = {
interval: setInterval(() => this.calcNextGeneration(), ms)
};
calcNextGeneration() {
console.log("calcNextGeneration", this.props.gameBoard.running);
if( !this.props.gameBoard.running ) return;
...