Open plh97 opened 4 years ago
function CombineReducer(reducers) { return function combine(state, action) { const newState = {}; Object.keys(reducers).forEach((key) => { newState[key] = reducers[key](state[key], action); }); return newState; }; } const CreateStore = (combination, initState, rewriteCreateStore) => { if (typeof initState === 'function') { return initState(CreateStore)(combination); } if (rewriteCreateStore) { return rewriteCreateStore(CreateStore)(combination, initState); } let state = {}; const listeners = []; function subscript(cb) { listeners.push(cb); return function unsubscript() { listeners.splice(listeners.indexOf(cb), 1); }; } function getState() { return state; } function dispatch(action) { state = combination(state, action); listeners.forEach((cb) => { cb(); }); } dispatch({ type: Symbol(1) }); return { subscript, getState, dispatch, }; }; function ApplyMiddleware(middlewares) { return function rewriteCreateStoreFunc(oldCreateStore) { return function newCreateStore(reducer, initState) { const store = oldCreateStore(reducer, initState); let { dispatch } = store; const chains = middlewares.map((middleware) => middleware({ getState: store.getState })); chains.reverse().forEach((chain) => { dispatch = chain(dispatch); }); store.dispatch = dispatch; return store; }; }; } export { CombineReducer, CreateStore, ApplyMiddleware, };
redux原理全解 | 前端面试与进阶指南
视频解说: https://www.youtube.com/watch?v=QOUao86FPxg
实现步骤
代码
Reference
redux原理全解 | 前端面试与进阶指南