export let createStore = (reducer)=>{ //定義默認的state let state = {}; //定義默認的action let actionTypes = "@@redux/INIT"+Math.random(); let initAction = {type:actionTypes} //將所以需要監聽的函數放在這個里面 let listeners = [] //定義getState函數 let getState = ()=>state; //定義事件訂閱函數 let subscribe = (cb)=>{ listeners.push(cb); } //定義事件派發函數 用來調用action let dispatch = (action=initAction)=>{ //調用reducer獲取新的state state = reducer(state,action); //遍歷所以需要監聽的函數 listeners.map((cb)=>{ cb(); }) } dispatch(); return { getState, dispatch, subscribe } }
const combineReducers = (reducers)=>{
let newState = {};
return function(state,action){
for(var key in reducers){
newState[key] = reducers[key](state[key],action)
}
return newState;
}
}