开始阅读前先回顾一下Redux的几个基本的API
const store = createStore(reducer)store.dispatch(action)发起一个动作让reducer匹配const state = store.getState()获取当前的statestore.subscribe(listener)添加监听,每次dispatch都会触发监听函数bindActionCreators(actions,dispatch)具体的调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17const reducer = (state=initialState,action){
switch(action.type){
case add:
return state+1;
case delete:
return state-1;
default:
return 0;
}
}
const store = createStore(reducer)
const state = store.getState()
const listener = () =>{
console.log(`现在有${store.getState()把枪}`)
}
store.subscribe(listener);
store.dispatch({type:add})
Redux/createStore的简单实现
先理清思路
- createStore函数创建的对象有getState、dispatch、subscribe方法
- 创建完就可以获取到初始值default,那么在内部是不是就默认dispatch了一个特别特别特殊的action,来区别用户的action.type
- 每次dispatch都会触发subscribe订阅的监听函数
1 | export function createStore(reducer){ |
bindActionCreator实现:其实就是给action绑定上dispatch
1 | // function bindActionCreator(action,dispatch){ |