redux(二)- 实现
实现简易版的 createStore 及 combineReducers。
createStore#
createStore:创建一个 Redux store 来以存放应用中所有的 state。应用中应有且仅有一个 store。
参数#
reducer#
- Type: Function
- Required
接收两个参数,分别是当前的 state 树和要处理的 action,并返回新的 state 树。
preloadedState#
- Type: any
State 的初始值,
enhancer#
- Type: Function
用于组合 store creator 的高阶函数,返回一个新的强化过的 store creator。这与 middleware 相似,它也允许你通过复合函数改变 store 接口。
返回值#
Store#
- Store.getState 获取状态树 state
- Store.dispatch 修改状态树的唯一方式
- Store.subscribe 订阅,接收一个函数,并返回解约函数,当状态改变时触发
实现#
根据 Redux 核心概念及函数定义,实现 createStore 简易版如下:
combineReducers#
参数#
reducers#
- Type: Object
- Required
返回值#
rootReducer#
- Type: Function