• 手写 redux


    代码:

    // 我们知道 createStore 返回三个函数 { subscribe, dispatch, getState }
    // 并且需要传入一个reducers
    
    function reducer(state = 0, action) {
      switch (action.type) {
        case "INCREMENT":
          return state + 1;
        case "DECREMENT":
          return state - 1;
        default:
          return state;
      }
    }
    
    const createStore = (reducer) => {
      let currentState; //  state
      let observers = []; // 观察者队列
    
      // 直接返回当前状态
      function getState() {
        return currentState;
      }
    
      // 触发reducers内的方法,更改 state
      function dispatch(action) {
        currentState = reducer(currentState, action);
        observers.forEach((fn) => fn());
      }
    
      // subscribe 将传入的回调加入观察者队列,触发dispatch的时候会触发所有回调
      // redux 使用了 proposal-observable 这个库的观察者模式
      function subscribe(cb) {
        observers.push(cb);
      }
    
      // 初始化store数据
      dispatch({ type: "INIT_SATATE" });
      return { getState, dispatch, subscribe };
    };
    
    export const store = createStore(reducer);
    
    store.subscribe(() => {
      console.log(store.getState());
    });
    

    .

  • 相关阅读:
    第一次热身赛和正式比赛感想
    简明解释算法中的大O符号
    poj 3045
    poj 3104
    poj 3273
    poj 3258
    poj 2456
    二分法小结
    Poj 2718 Smallest Difference
    GCJ——Crazy Rows (2009 Round 2 A)
  • 原文地址:https://www.cnblogs.com/crazycode2/p/13372188.html
Copyright © 2020-2023  润新知