Board logo

标题: 使用 Redux 实现时间旅行(4) [打印本页]

作者: look_w    时间: 2018-11-18 19:58     标题: 使用 Redux 实现时间旅行(4)

更高级的缩减程序在   中,您了解了如何组合使用缩减程序与 Redux combineReducers() 函数。图书搜索应用程序的最终版本组合了 4        个缩减程序,如清单 9 所示。
清单 9. 组合后的缩减程序 (reducers.js)        
1
2
3
4
5
6
7
8
// Combine reducers

export default combineReducers({
    books:         fetchReducer,
    topic:         topicReducer,
    currentStatus: statusReducer,
    displayMode:   bookDisplayReducer
});




清单 10 给出了在包含时间旅行功能后,图书搜索应用程序的经过改良的缩减程序。
清单 10. 更高级的 undo          缩减程序        (reducers.js)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { combineReducers } from 'redux';
import { store } from './store';
import stateHistory from './statehistory';

...

const undo = reducer => (state = stateHistory.present, action) => {
  switch(action.type) {
    case 'UNDO':
      stateHistory.undo();
      break;

    case 'REDO':
      stateHistory.redo();
      break;

    case 'GOTO':
      stateHistory.gotoState(action.stateIndex);
      break;

    default:
      const newState = reducer(state, action);
      stateHistory.push(newState);
  }

  return stateHistory.present;
}

// Combine reducers

export default undo(combineReducers({
    books:         fetchReducer,
    topic:         topicReducer,
    currentStatus: statusReducer,
    displayMode:   bookDisplayReducer
}));




在清单 10 中,undo() 函数是一个接受另一个缩减程序作为参数的缩减程序。当前操作与历史无关时,即操作类型不是          UNDO、REDO 或 GOTO 时,undo          函数会使用该缩减程序计算下一个状态。在这种情况下,在包含的缩减程序计算出该状态后,undo 函数会该状态推送到历史堆栈上。
当操作与历史相关时,undo 函数被委托给合适的状态历史方法。无论当前操作是否与历史相关,undo() 函数都会返回          stateHistory 对象当前定义的现在状态。
使用另一个缩减程序来确定下一个状态的缩减程序(比如 undo 函数)被称为高级 缩减程序,您可将它们视为   的等效函数。




欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) Powered by Discuz! 7.0.0