Redux Reducer不会设置布尔对象属性

时间:2017-04-05 15:13:39

标签: reactjs redux reducers

除了未设置的布尔变量外,我还有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仍为假。

为什么?

完整的笔:http://codepen.io/lafisrap/pen/yMZyXw

1 个答案:

答案 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;
...