zoukankan      html  css  js  c++  java
  • 面试之redux的简单实现

    为啥使用redux略过...

    demo地址

    一般项目中使用redux时,会和react-redux配合使用,如果不使用react-redux时,redux也可以单独工作,使用react-redux会简化一些操作

    reudx包暴露了几个方法

    • createStore
    • combineReducer
    • applyMiddleware
    • bindActionCreators

    createStore

    其中createStore是其中的核心方法,只使用其中一个就可以单独使用

    根据上面的使用流程可以实现以下方法

    function createStore(reducer, prePayload) {
    
      let currentState = prePayload;
      let listeners = [];
    
      function getState() {
        return currentState;
      }
    
      function dispatch(action) {
        currentState = reducer(currentState, action);
    
        for(let i = 0; i < listeners.length; i++) {
          listeners[i]();
        }
      }
    
      function subscribe(func) {
        let isSubscribed = false;
    
        if (typeof func === 'function') {
          if (!listeners.includes(func)) {
            listeners.push(func);
            isSubscribed = true;
          }
        }
    
        return function unSubscribe() {
          if (!isSubscribed) {
            return;
          }
    
          let index = listeners.indexOf(func);
          listeners.splice(index, 1);
        }
      }
    
      dispatch({type: 'INIT'});
    
      return {
        getState,
        dispatch,
        subscribe,
      }
    }
    

    combineReducer

    这个函数的意义是可以整合reducer函数,这样可以方便分模块定义redux
    实现原理就是定义一个顶级对象,使用key来区分(key是传入combineReducers的对象的key),当派发一个action时,循环所有的reducer函数,更新所有的模块

    export default function combineReducers(reducers) {
      const reducerKeys = Object.keys(reducers);
    
      return function combine(state = {}, action) {
    
        let nextState = {};
        let isChanged = false;
    
        for(let i = 0; i < reducerKeys.length; i++) {
          let key = reducerKeys[i];
          let reducer = reducers[key];
          let stateForKey = state[key];
    
          nextState[key] = reducer(stateForKey, action);
          isChanged = isChanged || nextState !== state;
        }
    
        return isChanged ? nextState : state;
      }
    }
    
  • 相关阅读:
    Linux学习之CentOS(十三)--CentOS6.4下Mysql数据库的安装与配置
    python 对数函数
    Python使用os.listdir()函数来得目录内容的介绍
    Linux下基于HTTP协议带用户认证的GIT开发环境设置
    在python中如何设置当前工作目录
    Python 获得命令行参数的方法
    Python time mktime()方法
    linux中怎样从底部向上查看log文件
    python基础之使用os.system来执行系统命令
    python datetime处理时间
  • 原文地址:https://www.cnblogs.com/changzhenan/p/10686042.html
Copyright © 2011-2022 走看看