Redux 源码自己写了一遍
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
</head>
<body>
<script type='text/javascript'>
// var f = function( ...arg ){
// arg 是个数组
// ...arg 是传递进来的原封不动的值
// } // const reducer = function(state, action){
// if(!state){
// state = initialState;
// }
// let nextState = _.deepClone(state); // switch(action.type){
// case 'ADD_TODO':
// nextState.todos.push( action.payload );
// break;
// case 'INCREASE':
// nextState.counter = nextState.counter++;
// break;
// default:
// break;
// } // return nextState;
// } /*** compose ***/
// compose(func3, func2, func1)(0);
// 相当于写了 func3( func2( func1(0) ) )
const compose = function( ...funcs ) {
// 若没有传递参数, 则直接返还1个函数
if ( funcs.length === 0 ) {
return arg => arg;
} // 若只有1个参数, 则直接返还这个函数
if ( funcs.length === 1 ) {
return funcs[0];
} // 取出最后1个函数 当作 reduceRight的第2个参数
const last = funcs[funcs.length - 1];
// 取除了最后一个函数以外的函数数组
const rest = funcs.slice(0, -1);
// 所传递进来的参数 都当作 最后1个函数的参数
return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args))
} /*** combineReducers ***/
const combineReducers = function(obj){
return function(state, action){
// nextState 为返回的新 state
let nextState = {};
for(var item in obj){
// obj[item] 为item 对应的reducer
/*
state[item] 的意思是 state 对应与 item 上的值,
比如 state 为 { counter: 0}, state[item]的值就为 0
*/
nextState[item] = obj[item]( state[item], action );
}
return nextState;
}
} /*** bindActionCreators ***/
const bindActionCreators = (obj, dispatch) => {
let objNew = {};
for(let i in obj){
// item 为创建 action 的函数
let item = obj[i];
objNew[i] = (...args) => {
dispatch( item(...args) );
}
}
return objNew;
} /*** applyMiddleware ***/
// 传入所有的中间件
const applyMiddleware = (...middlewares) => {
// 可以传入 createStore 作为参数
return (createStore) => {
// 这一步已经生成了 增强版本的 createStore
return (reducer, initialState, enhancer) => { let store = createStore(reducer, initialState, enhancer); // 这一步原来的写法是
// let chain = middlewares.map( middleware => middleware(store) );
// 源代码里是 从新创建了一个store
let storeNew = {
getState: store.getState,
dispatch: (action) => dispatch(action)
}
let chain = middlewares.map( middleware => middleware(storeNew) ); // 只有最后1个函数的传入了 store.dispatch 当作 dispatch,
// 其它函数都是最后1个函数的返回值当作 dispatch
const dispatch = compose(...chain)(store.dispatch); /*
最早本来想下面那样写,
这个结果是所有中间件的 dispatch 都为 store.dispach let chain = [...middlewares].map( (item) => {
return item(store)(store.dispatch);
} ); const dispatch = (action) => {
compose(...chain)(action);
}; 打印的结果为: 3 dispatch before
3 dispatch after
2 dispatch before
2 dispatch after
1 dispatch before
1 dispatch after */ return {
getState: store.getState,
subscribe: store.subscribe,
replaceReducer: store.replaceReducer,
dispatch: dispatch
}
}
}
} /*** createStore ***/
const createStore = function(reducer, initialState, enhancer){
if( typeof enhancer === "function"){
return enhancer(createStore)(reducer, initialState);
} let state = initialState;
// 操作的 listeners
let listeners = [];
let listenersCache = listeners; // 但凡 listeners 有变化, 比如push了 或者删除了, 都提前执行下 ensure
const ensure = function(){
// 若相等, 则拷贝一个新的 listeners
if( listeners == listenersCache ){
listeners = listenersCache.slice();
}
} const getState = function(){
return state;
} const dispatch = function(action){
state = reducer(state, action); // 为了让 ensure 执行成功
listenersCache = listeners;
let len = listenersCache.length;
for(let i = 0; i < len; i++){
listenersCache[i]();
} return action;
} const subscribe = listener => {
ensure();
listeners.push(listener); return function(){
ensure();
listeners = listeners.filter(function(item, i){
return item != listener;
});
} } dispatch({});
return {
dispatch: dispatch,
getState: getState,
subscribe: subscribe
}
} const initialState = {
counter: 0,
todos: []
} const counterReducer = function(counter = 0, action){
switch(action.type){
case 'INCREASE':
console.log('Reducer increase');
return counter = counter + 1;
default:
return counter;
}
} const todosReducer = function(todos = [], action){
switch(action.type){
case 'ADD_TODO':
return [...todos, action.payload];
default:
return todos;
}
} const rootReducer = combineReducers({
counter: counterReducer,
todos: todosReducer
}); const actionAdd = (n) => {
return {type: n}
} const store = createStore(rootReducer, initialState); const actionCreate = bindActionCreators(
{actionAdd: actionAdd},
store.dispatch
); store.subscribe(function(){
console.log( store.getState() );
}); store.dispatch( actionAdd('INCREASE') );
actionCreate.actionAdd('INCREASE');
store.dispatch({type: 'ADD_TODO', payload: 'hello world'}); console.log(' ---------- 分割线 ---------- '); // 中间件 1
// 根据源代码 middlewareAPI 是一个新的对象, 类似 store
// 只有store 里的dispatch 和 getState方法
const middleware1 = ( middlewareAPI ) => {
return (dispatch) => {
return (action) => {
console.log( '1 dispatch before' ); // 这个 dispatch 其实是 middleware2 里的函数 (action) => {...}
let actionReturn = dispatch(action); console.log( '1 dispatch after' );
return actionReturn;
}
}
}; const middleware2 = ( middlewareAPI ) => {
return (dispatch) => {
return (action) => {
console.log( '2 dispatch before' ); // 这个 dispatch 其实是 middleware3 里的函数 (action) => {...}
let actionReturn = dispatch(action); console.log( '2 dispatch after' );
return actionReturn;
}
}
}; const middleware3 = ( middlewareAPI ) => {
return (dispatch) => {
return (action) => {
console.log( '3 dispatch before' ); // 这个 dispatch 才是 store.dispatch, 最终只有这里调用 reducer 更新
let actionReturn = dispatch(action); console.log( '3 dispatch after' );
return actionReturn;
}
}
}; let enhancedCreateStore = applyMiddleware(middleware1, middleware2, middleware3)(createStore);
let storeEnhance = enhancedCreateStore(rootReducer, initialState); /*
最后的打印结果是: 1 dispatch before
2 dispatch before
3 dispatch before
Reducer increase
3 dispatch after
2 dispatch after
1 dispatch after
*/
storeEnhance.dispatch({type: 'INCREASE'}); </script>
</body>
</html>
Redux 源码自己写了一遍的更多相关文章
- redux源码解读(二)
之前,已经写过一篇redux源码解读(一),主要分析了 redux 的核心思想,并用100多行代码实现一个简单的 redux .但是,那个实现还不具备合并 reducer 和添加 middleware ...
- redux源码解读(一)
redux 的源码虽然代码量并不多(除去注释大概300行吧).但是,因为函数式编程的思想在里面体现得淋漓尽致,理解起来并不太容易,所以准备使用三篇文章来分析. 第一篇,主要研究 redux 的核心思想 ...
- Redux 源码解读 —— 从源码开始学 Redux
已经快一年没有碰过 React 全家桶了,最近换了个项目组要用到 React 技术栈,所以最近又复习了一下:捡起旧知识的同时又有了一些新的收获,在这里作文以记之. 在阅读文章之前,最好已经知道如何使用 ...
- 从Redux源码探索最佳实践
前言 Redux 已经历了几个年头,很多 React 技术栈开发者选用它,我也是其中一员.期间看过数次源码,从最开始为了弄清楚某一部分运行方式来解决一些 Bug,到后来看源码解答我的一些假设性疑问,到 ...
- redux源码浅入浅出
运用redux有一段时间了,包括redux-thunk和redux-saga处理异步action都有一定的涉及,现在技术栈转向阿里的dva+antd,好用得不要不要的,但是需要知己知彼要对react家 ...
- redux源码解读
react在做大型项目的时候,前端的数据一般会越来越复杂,状态的变化难以跟踪.无法预测,而redux可以很好的结合react使用,保证数据的单向流动,可以很好的管理整个项目的状态,但是具体来说,下面是 ...
- Redux源码学习笔记
https://github.com/reduxjs/redux 版本 4.0.0 先了解一下redux是怎么用的,此处摘抄自阮一峰老师的<Redux 入门教程> // Web 应用是一个 ...
- redux源码阅读之compose,applyMiddleware
我的观点是,看别人的源码,不追求一定要能原样造轮子,单纯就是学习知识,对于程序员的提高就足够了.在阅读redux的compose源码之前,我们先学一些前置的知识. redux源码阅读之compose, ...
- 带着问题看redux源码
前言 作为前端状态管理器,这个比较跨时代的工具库redux有很多实现和思想值得我们思考.在深入源码之前,我们可以相关注下一些常见问题,这样带着问题去看实现,也能更加清晰的了解. 常见问题 大概看了下主 ...
随机推荐
- 【Dream Counting, 2006 Dec-数数的梦】数位dp
题意:给定两个数,问区间[A,B]中0~9分别出现了多少次.A,B<=10^18 题解:应该是最裸的数位dp吧..一开始没有记忆化tle了TAT 我们可以求出区间[0,B]的,再减去区间[0,A ...
- 【BZOJ】1833 [ZJOI2010]count 数字计数
[算法]数位DP [题解] 记忆化搜索 #include<cstdio> #include<algorithm> #include<cstring> #define ...
- 转一篇sublime必备的一些插件
Package Control 功能:安装包管理 简介:sublime插件控制台,提供添加.删除.禁用.查找插件等功能 使用:https://sublime.wbond.net/installatio ...
- hdu 1395 2^x mod n = 1(暴力题)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1395 2^x mod n = 1 Time Limit: 2000/1000 MS (Java/Oth ...
- 开源网络准入系统(open source Network Access Control system)
开源网络准入系统(open source Network Access Control system) http://blog.csdn.net/achejq/article/details/5108 ...
- VPS性能综合测试(5):UnixBench工具介绍
UnixBench 介绍 UnixBench 是一个类 unix (Unix, BSD, Linux 等) 系统下的性能测试工具,它是一个开源工具.可以用于测试系统主机的性能. UnixBench 进 ...
- jQuery -《锋利的jQuery》————读后小结
jQuery是一个优秀的javascript库. 我用的是vs2012自带的 jquery-1.8.2.js这个库,在Scripts这个文件夹下面 首先,我们使用jQuery要在head标签内引入j ...
- 创建.dat文件(转载)
比较有用的东比较有用的东西 首先,批处理文件是一个文本文件,这个文件的每一行都是一条DOS命令(大部分时候就好象我们在DOS提示符下执行的命令行一样),你可以使用DOS下的Edit或者Windows的 ...
- sql server中字符串无法替换空格的问题
直接上代码: select case when 'workReport'=LTRIM(RTRIM(' workReport ')) then 'trim去空格成功' when 'workReport' ...
- Longest Valid Parentheses——仍然需要认真看看(动态规划)
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...