实现功能
在上一节的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 };
}