核心功能
- getState 獲取當前的state
- dispatch 派發(fā)action以更新狀態(tài)
- subscribe 訂閱與退訂
- 生成actionCreator
- 合并reducer
1 getState
function getState(){
return currentState;
}
2 dispatch
function dispatch(action){
currentState = currentReducer(state, action)
listeners.forEach(fn => fn())
}
3 訂閱
let listeners = []
function subscribe(listener){
listeners.push(listener)
return function(){
listeners.filter(fn => fn !== listener)
}
}
4 合并reducers
function combineReducers(reducers){
let combineState;
Object.keys(reducers).forEach(name => {
combineState[name] = reducers[name](state, action)
})
return combineState
}
function createStore(reducer) {
let currentState;
let currentReducer = reducer;
let listeners = [];
function getState() {
return currentState;
}
function dispatch(action) {
currentState = currentReducer(currentState, action);
listeners.forEach(l => l())
}
function subscribe(listener) {
listeners.push(listener);
return function () {
listeners.filter(fn => fn!= listener)
}
}
function combineReducer(reducers){
return function(state = {}, action){
let combineState = {}
Object.keys(reducers).forEach(name => {
combineState[name] = reducers[name](state, action)
})
return combineState;
}
}
dispatch({
type: '@@redux/INIT'
})
return {
getState,
dispatch,
subscribe
}
}
export { createStore }
中間件原理
主要是改裝dispatch