Redux中的actions用来表明发生了什么,Reducers基于action来对state进行更新。那么Store就是action和Reducers之间的桥梁。它的功能如下:
- 存储应用的所有state
- 通过其getState()方法获取state
- 通过其dispatch(action)来更新state
- 通过其subscribe(listener)来注册监听器
- 取消subscribe(listener)返回的监听器
Store的创建方式很简单,只要执行createStore(reducers)
即可。
下面我们来看下dispatch的主要源码:
function dispatch(action) {
try {
isDispatching = true
//执行Reducers来更新state
currentState = currentReducer(currentState, action)
} finally {
isDispatching = false
}
//触发监听器的执行,依据最新的state来进行处理
const listeners = currentListeners = nextListeners
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i]
listener()
}
return action
}