zoukankan      html  css  js  c++  java
  • 手写 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());
    });
    

    .

  • 相关阅读:
    JVM基础(一)—— 运行时内存结构
    SQL if 和 case when查询示例
    SQL分组聚合查询
    My music
    DataX增量同步到ADB ADS时报错
    shell find的用法
    pycharm安装
    在两个库中查找出差异明细
    docker下安装centos
    升级RDS8.0遇到的问题
  • 原文地址:https://www.cnblogs.com/crazycode2/p/13372188.html
Copyright © 2011-2022 走看看