classcreateStore{constructor(reducer, preloadedState, enhancer){this.currentReducer = reducer;this.currentState = preloadedState;this.currentListeners =[];this.nextListeners =this.currentListeners;this.isDispatching =false;}ensureCanMutateNextListeners=()=>{if(this.nextListeners ===this.currentListeners){this.nextListeners =this.currentListeners.slice();}}getState=()=>{if(this.isDispatching){thrownewError('The reducer has already received the state as an argument.')}returnthis.currentState;}subscribe= listener =>{if(typeof listener !=='function'){thrownewError('Expected the listener to be a function.');}if(this.isDispatching){thrownewError('component and invoke store.getState() in the callback to access the latest state.')}let isSubscribed =true;this.ensureCanMutateNextListeners();this.nextListeners.push(listener);returnfunctionunsubscribe(){if(!isSubscribed){return;}if(this.isDispatching){thrownewError('You may not unsubscribe from a store listener while the reducer is executing. ')}
isSubscribed =false;// 控制注销只执行一次this.ensureCanMutateNextListeners();const index =this.nextListeners.indexOf(listener);this.nextListeners.splice(index,1);this.currentListeners =null;}}dispatch= action =>{if(typeof action.type ==='undefined'){thrownewError('Actions may not have an undefined "type" property. ')}if(this.isDispatching){thrownewError('Reducers may not dispath actions')}try{this.isDispatching =true;this.currentState =this.currentReducer(this.currentState, action)}finally{this.isDispatching =false;}const listeners =(this.currentListeners =this.nextListeners)for(let i =0; i < listeners.length; i++){const listener = listeners[i];listener();}
console.log(reducer);return action
}}constreducer=(state ={ count:0}, action)=>{switch(action.type){case'INCREASE':return{ count: state.count +1};case'DECRESE':return{ count: state.count -1};default:return state;}}const store =newcreateStore(reducer);
store.subscribe(()=>{
console.log(store.getState());})const actions ={
increase:()=>({
type:'INCREASE'}),
decrese:()=>({
type:'DECREASE'})}
store.dispatch(actions.increase());
store.dispatch(actions.increase());
store.dispatch(actions.increase());