开始阅读前先回顾一下Redux的几个基本的API
const store = createStore(reducer)
store.dispatch(action)
发起一个动作让reducer匹配
const state = store.getState()
获取当前的state
store.subscribe(listener)
添加监听,每次dispatch都会触发监听函数
bindActionCreators(actions,dispatch)
具体的调用
const 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订阅的监听函数
export function createStore(reducer){
let currentState = {};
let currentListeners = [];
function getState(){
return currentState;
}
function subscribe(listener){
currentListener.push(listener);
}
function dispatch(action){
currentState = reducer(currentState,action);
currentListeners.forEach(v=>v())
return action
}
dispatch({type:'@huangbin-redux-study'})
return {getState,subscribe,dispatch}
}
bindActionCreator实现:其实就是给action绑定上dispatch
export function bindActionCreators(actions,dispatch){
const bound = {};
Object.keys(actions).forEach(item=>{
bound[item] = (...args) =>dispatch(actions[item](...args));
})
console.log(bound);
return bound;
}