React.js/Redux:Reducers中的setInterval和clearInterval

Ale*_*dro 7 setinterval reducers reactjs redux react-redux

目前我正在研究FCC生命游戏,我能够弄清楚如何生成下一个应用程序状态(递增).

话虽这么说,我的下一步是弄清楚如何连续生成新的应用程序状态(生成).在这种情况下,我试图在我的reducer中实现setInterval和clearInterval .

我希望能够启动/暂停生成新一代(通过在state.start中切换状态)

我实现它的麻烦是范围问题.

这是我的减速机的一部分:

减速器/ reducers_grid.js

export default function(state = initialState, action){
  switch (action.type) {
    ....
    case START:
      let toggleStart = state.start === true ? false : true;

      if (state.start === true){
        console.log('START THE GAME')

        const newGeneration = nextGeneration(action.payload,state)
        return Object.assign({}, state, {cells: newGeneration, start: toggleStart })
      }
      else {
        console.log('PAUSE THE GAME')
        return Object.assign({}, state, {start: toggleStart })
      }

  return state;
}
Run Code Online (Sandbox Code Playgroud)

从本质上讲,nextGeneration函数会生成新的应用程序状态(生成)并通过Object.assign将其更新

首先,我想将setInteveral放在第一个if语句中,将clearInterval放在第二个if语句中,但显然会产生范围问题.

这部分逻辑似乎非常微不足道,但我一直坚持这一点.

小智 13

不要在减速机中这样做.减速器应该是纯函数(意味着没有副作用).相反,你可以创建在游戏运行时只渲染的成分(被设置为一个布尔状态trueSTART动作和falseSTOP动作).然后在组件的componentDidMount函数调用中调用setInterval一个调度NEXT_GENERATION动作的函数.之后,发送另一个动作,将计时器ID添加到商店.然后,在componentWillUnmount删除基于计时器ID的间隔.