坐在那里看源码很费劲,还是跟着手敲了一遍,把一些例子贴出来,能解有缘人的一丝疑惑也算是功德圆满。水平有限,但是挡不住我们进步的脚步 (∇*)

测试图片.png
constructor() { super(); console.log(''); console.log('--- parent constructor == start ----');
store.subscribe(() => { console.log('--- parent constructor == subscribe---', store.getState())
}); console.log('--- parent constructor == end----'); console.log('');
}
componentDidMount() { console.log(''); console.log('--- parent didMount == start ----');
store.subscribe(() => { console.log('--- parent didMount == subscribe---', store.getState())
}); console.log('--- parent didMount == end ----'); console.log('');
}
constructor(){ super(); console.log('==== child - dispatch === start --');
store.dispatch({ type: 'TO_PARENT'
}); console.log('==== child - dispatch === end ==');
}
import $$observable from 'symbol-observable'
store[$$observable]().subscribe({ next: (state) => { console.log('---$$observable--', state);
}
}); // 牛逼不,惊喜不??? 终究还是这些牛逼的人已经想到解决办法了,(^∇^*)
import $$observable from 'symbol-observable'// actionconst randomString = () =>
Math.random()
.toString(36)
.substring(7)
.split('')
.join('.')const ActionTypes = { INIT: `@@redux/INIT${randomString()}`, REPLACE: `@@redux/REPLACE${randomString()}`, PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`};// 判断一个obj是不是纯对象// 如果是纯对象,最底层的原型prototype都应该是继承自Objectfunction isPlainObject(obj) { if (typeof obj !== 'object' || obj === null) return false; let proto = obj; while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
} return Object.getPrototypeOf(obj) === proto;
}/**
* 读不懂,只能写着看看,o(╥﹏╥)o
* @param reducer
* @param preloadedState
* @param enhancer
*/export default function createStore(reducer, preloadedState, enhancer) { // preloadedState 是函数且 enhancer未定义
// enhancer 和 preloadedState 互换
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
enhancer = preloadedState;
preloadedState = undefined; console.log('===test==1=')
} // enhancer 是函数的时候使用如下方法
if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.')
} // 用enhancer包装一次,调用createStore,没有enhancer的方法
return enhancer(createStore)(reducer, preloadedState);
} // reducer 不是函数的时候
if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.');
} let currentReducer = reducer; let currentState = preloadedState; let currentListeners = []; let nextListeners = currentListeners; let isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { console.log('====arr-listener.slice====');
nextListeners = currentListeners.slice();
}
} // 获取当前的state
function getState() { if (isDispatching) { throw new Error( 'You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.'
)
} return currentState;
} /**
* 订阅的方法
* 1. 把当前的传入的listener放入队列
* 2. 在放入之前,更新队列应该确定是不是要复制一次初始的队列
* @param listener
* @returns {unsubscribe} 返回一个解除订阅的方法
*/
function subscribe(listener) { console.log('==== subscribe = inner ==='); if (typeof listener !== 'function') { throw new Error('Expected the listener to be a function.')
} if (isDispatching) { throw new Error( 'You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'
)
} let isSubscribed = true;
ensureCanMutateNextListeners(); // 复制一次当前的监听器队列
nextListeners.push(listener); // 将当前的监听器放入队列
// 返回一个取消订阅的方法
return function unsubscribe() { if (!isSubscribed) { return;
} if (isDispatching) { throw new Error( 'You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'
)
}
isSubscribed = false;
ensureCanMutateNextListeners(); const index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
}
} /**
* 事件派发
* 时间派发的时候做了两件事:
* 1. 用当前的reducer去修改state
* 2. 把订阅subscribe中的listener全部调用一遍
* @param action
* @returns {*}
*/
function dispatch(action) { // action 应该是一个纯对象 { }
if (!isPlainObject(action)) { throw new Error( 'Actions must be plain objects. ' + 'Use custom middleware for async actions.'
);
} // 派发必须是通过action.type
if (typeof action.type === 'undefined') { throw new Error( 'Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'
)
} // 判断是否在派发状态
if (isDispatching) { throw new Error('Reducers may not dispatch actions.');
} // 这块的作用感觉就是状态的切换,但是为什么呢??
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
} // 这里是执行的是subscribe中的回调函数
// ====> 注意这里是dispatch;却在调用subscribe的方法,注意
const listeners = (currentListeners = nextListeners); for (let i = 0; i
作者:Aaron_Alphabet
链接:https://www.jianshu.com/p/5da4338e6008
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3657/viewspace-2814415/ ,如需转载,请注明出处,否则将追究法律责任。