You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functioncreateStore(reducer,preloadedState,enhancer){// preloadedState、enhancer 不能同为函数,enhancer 为函数时,第四个参数不能为函数if(typeofpreloadedState==='function'&&typeofenhancer==='function'||typeofenhancer==='function'&&typeofarguments[3]==='function'){thrownewError('It looks like you are passing several store enhancers to '+'createStore(). This is not supported. Instead, compose them '+'together to a single function.');}// preloadedState、enhancer 同为函数时,preloadedState 复制给 enhancer,preloadedState 置为 undefinedif(typeofpreloadedState==='function'&&typeofenhancer==='undefined'){enhancer=preloadedState;preloadedState=undefined;}// 增强函数 enhancer 不为 undefined 时,执行增强函数,这个主要用来实现中间件的连接if(typeofenhancer!=='undefined'){if(typeofenhancer!=='function'){thrownewError('Expected the enhancer to be a function.');}// 增强函数returnenhancer(createStore)(reducer,preloadedState);}// reducer 不是函数抛错if(typeofreducer!=='function'){thrownewError('Expected the reducer to be a function.');}letcurrentReducer=reducer;// 存储当前 reducer,也用于 replaceReducer 替换letcurrentState=preloadedState;// 初始化 stateletcurrentListeners=[];// 订阅的回调数组letnextListeners=currentListeners;// 避免在发布通知调用用户回调函数时抛错影响了数组letisDispatching=false;// 防止在 reducer 中执行,getState、dispatch、subscribe、unsubscribe// currentListeners 数组浅拷贝,防止 dispatch 阶段执行用户回调抛错// 导致 dispatch 中断了,却影响了原来的数组结构 functionensureCanMutateNextListeners(){if(nextListeners===currentListeners){nextListeners=currentListeners.slice();}}// 获取 currentStatefunctiongetState(){}// 订阅消息,即 listener 入 currentListeners 队列functionsubscribe(listener){}// 根据 action.type 执行 reducer 函数,触发 state 更新,让后发布通知即遍历 nextListeners 执行functiondispatch(action){}// 动态更换 reducer,然后根据新的 reducer 初始化一次 statefunctionreplaceReducer(nextReducer){}// 为了支持未来 Observable 新特性,还在提案阶段,不讨论// function observable() {}// type 为一个随机字符串不会和 reducer 中的任何 type 相匹配// 如果 reducer 没有默认匹配,则初始化的 state 为 preloadedStatedispatch({type: ActionTypes.INIT});conststore={
getState,
subscribe,
dispatch,
replaceReducer,};returnstore;}
redux 源码分析
原文链接
简介
三大原则
对比 mobx
而 mobx 一般对于一个页面或页面级别的组件创建 store,然后在一个总文件中导入,作为一个大对象导出给 context。
而 mobx
@observable state
可以随意改变,甚至逻辑分散在视图 view 层,例如onClick={() => (state.status = 1)}
。虽然官方建议把逻辑封装在 action 中,例如
@action updata() {}
,但不是一种强约束。state.xx = 1; return state
,应该是return { ...state, xx: 1}
。而鉴于 mobx 的机制, mobx 更别说了。
所以常说,mobx 常用中小型应用,redux 更适合大型应用。
概览
使用
例子都是摘录来的,不想看的可以跳过。
深入 redux
createStore
到此最重要的 createStore 函数就实现完毕。接下来分析两个辅助函数 bindActionCreators,combineReducers,最后分析实现中间件功能的 compose、applyMiddleware。
bindActionCreators
combineReducers
compose
applyMiddleware
thunk 中间件
applyMiddleware(a, b)
,a 中的 next 就是 b 中返回的 action => {} 函数,b 中的 next 就是 store.dispatch。这样就串起来了。总结
完。
The text was updated successfully, but these errors were encountered: