function createStore(reducer, initialState) {
let currentReducer = reducer;
let currentState = initialState;
let listener = () => { };
return {
getState() {
return currentState;
},
dispatch(action) {
currentState = currentReducer(currentState, action);
listener();
return action;
},
subscribe(newListener) {
listener = newListener;
}
}
}
function counter(state = 0, action) {
switch (action.type) {
case "ADD":
return state + 1;
case "MINUS":
return state - 1;
default:
return state;
}
}
let store = createStore(counter);
store.subscribe(() => {
console.log(store.getState())
})
store.dispatch({ type: 'ADD' })
store.dispatch({ type: 'MINUS' })
store.dispatch({ type: 'ADD' })
转载于:https://my.oschina.net/u/3117745/blog/1787958