【问题标题】:Redux Reducer won't set boolean object propertyRedux Reducer 不会设置布尔对象属性
【发布时间】:2017-04-05 23:44:59
【问题描述】:

我有一个可以工作的 Redux 减速器,除了一个未设置的布尔变量。代码:

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: 真

但容器中的值:this.props.gameBoard.running 仍然是 false。

为什么?

全笔:http://codepen.io/lafisrap/pen/yMZyXw

【问题讨论】:

  • 人生游戏正在运行和停止?

标签: reactjs redux reducers


【解决方案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;
...

【讨论】:

    猜你喜欢
    • 2016-01-05
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    相关资源
    最近更新 更多