Open zhangyanan0525 opened 6 years ago
中间件机制关键代码实现
let funcs = [
(next)=>(action)=>{console.log(1);next(action);console.log(2)},
(next)=>(action)=>{console.log(3);next(action);console.log(4)}
]
let dispatch = (action)=>{
console.log(action)
}
const compose = function(funcs){
return funcs.reduce((a,b)=>{
return (dispatch)=>a(b(dispatch))
})
}
dispatch = compose(funcs)(dispatch)
dispatch('我派发了action')
~~
redux源码解析
redux源码地址
redux主要代码的目录结构
接下来我们按照redux的官方网站提供的redux使用示例,来一步步看下每个函数的作用
根据示例,可以看出来,我们首先是定义许多actions,并且分别定义了两个reducer函数,然后通过combineReducers将两个reducer合并在一起,然后做为createStore的参数传入,并执行。 我看网上其他人的解析都是先分析createStore,但是我觉得应该从combineReducers开始。
combineReducers
重要的两行代码是:
我们根据这两行代码去找源码 我们找到了源码,原来就是这个combineReducers函数。我们看一下这个函数做了什么事情。(教大家一个小技巧,我们在看源码的时候,为了防止很多细节的代码,对主干代码的干扰,我们可以将大部分代码都合起来,需要看的时候再打开。)现在我们看到,combineReducers接受一个叫reducers的参数,返回一个闭包函数combination。 那么在返回这个combination函数之前,那一大坨代码干了什么事情呢?现在可以打开代码了,我们来看一下主要内容。
代码1部分,整个部分其实是为了生成一个finalReducers,让闭包使用。我们在使用redux的时候,单个reducer(todos, visibilityFilter)都应该定义成Function。这部分代码就是做了判断,看看这些单个reducer函数是不是undefined或是不是function,只有是function的才能幸运的进入finalReducers这个变量。 代码2部分大体就是一些数据格式的判断,有问题会报错。我没细看不影响大局。 好了我们再来看一遍redux官网给出的使用示例: 在reducers/index.js文件中,输出的其实就是combination闭包函数
然后在index.js文件中,将combination函数起个名字rootReducer传入了createStore里。
好。那么我们可以开始分析createStore了
createStore
我们还是把细节代码合上,只看主干
applyMiddleware
先看官网是如何使用applyMiddleware的。
const crashReporter = store => next => action => { try { return next(action) } catch (err) { console.error('Caught an exception!', err) Raven.captureException(err, { extra: { action, state: store.getState() } }) throw err } }
import { createStore, combineReducers, applyMiddleware } from 'redux'
const todoApp = combineReducers(reducers) const store = createStore( todoApp, // applyMiddleware() tells createStore() how to handle middleware applyMiddleware(logger, crashReporter) )