【react】---手动封装一个简易版的redux
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
    }
}

 

 
【react】---手动封装一个简易版的redux
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
    }
}

 

 

相关文章:

  • 2022-03-09
  • 2021-09-08
  • 2022-12-23
  • 2022-03-06
  • 2022-12-23
  • 2021-12-26
  • 2021-09-11
  • 2019-08-14
猜你喜欢
  • 2022-12-23
  • 2021-04-01
  • 2022-12-23
  • 2018-06-15
  • 2022-12-23
  • 2020-07-09
  • 2021-10-13
相关资源
相似解决方案