react中對於redux的封裝

const createStore = (reducer)=>{
    //默認的state對象
    let state = {};

    //將全部訂閱的事件存在在這個數組中
    let listeners = [];

    //默認的action
    let actionTypes = "@@redux/INIT";
    let Initaction = {
        type:actionTypes
    }

    const dispatch = (action=Initaction)=>{
        state = reducer(state,action);
        listeners.map(cb=>{
            cb();
        })
    }
    dispatch();

    const getState = ()=>state;

    const subscribe = (cb)=>{
        listeners.push(cb);
    }


    return {
        dispatch,
        getState,
        subscribe
    }
}

const combineReducers = (reducers)=>{

    const newState = {};

    return function(state,action){
        for(let key in reducers){
            let reduce = reducers[key];
            
            console.log(newState[key])
            newState[key] = reduce(state[key],action);
        }
        return newState;
    }
}



export {createStore,combineReducers}
相關文章
相關標籤/搜索