如何实现一个精简版的redux

实现功能

在上一节的React学习案例中,引用了redux库中的CreateStore函数和combineReducers函数,用于创建Store容器和组合多个Reducer。

import { combineReducers } from 'redux';
import { createStore } from 'redux';

现在的工作就是实现一个精简版的redux来替代这两个函数也能正常工作

import { createStore,combineReducers } from './actions/myRedux';

实现步骤

1、在src路径下创建一个action文件夹,然后在action中创建js文件myRedux
2、在myRedux.js中首先实现combineReducers函数,函数功能及注释如下:

//合并多个reduce方法,且每个reduce有自己特有的state。
//功能时在调用一个dispatch处理action时会依次调用每个reduce来处理该aciton
//输入参数格式:
/*  reduce1中的state表示为store.getState().add
  {
    add:reduce1,
    dec:reduce2
  }
  */
export function combineReducers(reducers){
  return (state = {}, action) => {
    return Object.keys(reducers).reduce(
      (nextState, key) => {
        //依次通过store.state.key调用了每个reduce,然后每个reduce返回了自己的state保存在了store.state.key中
        nextState[key] = reducers[key](state[key], action);
        return nextState;
      },
      {} 
    );
  };
}

3、在myRedux.js中首先实现createStore函数,createStore的功能是创建一个Store容器,容器中管理着一个state属性数据、当前绑定的监听函数listeners数组,然后可以通过getState方法获取stete属性、subscribe方法添加监听器函数、dispatch方法分发action任务,并且调用reducer方法执行action,并更新state,最后在调用listern监听函数。代码及注解如下:

export function createStore(reducer) {
  //数据属性
  let state;
  //监听函数数组
  let listeners = [];

  //获取state
  const getState = () => state;

  //分发action任务
  const dispatch = (action) => {
    state = reducer(state, action);//执行reduce并获取新的state
    //此时state已经更新,依次执行所有listener监听器方法
    listeners.forEach(listener => {
      console.log("监听函数刷新执行");
      listener();
    });
  };

  //绑定监听器方法
  const subscribe = (listener) => {
    //直接添加到listeners数值中即可
    listeners.push(listener);
    return () => {
      //filter:   array.filter(function (x) {return x % 2 !== 0;});)
      console.log("listeners filter前:"+listeners);
      listeners = listeners.filter((l) => {return l !== listener});//返回listeners中不同的listener
      console.log("listeners filter后:"+listeners);
    }
  };

  //先调用一次dispatch  以初始化state
  dispatch({});

  return { getState, dispatch, subscribe };
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值