react中对于redux的封装

本文深入解析了Redux的创建过程,包括store的初始化、action的分发机制、state的更新及订阅事件的处理。同时,详细介绍了combineReducers函数的实现方式,帮助读者理解如何将多个reducer合并成一个总reducer。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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}

 

转载于:https://www.cnblogs.com/Leslie-Cheung1584304774/p/10734672.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值