Redux 源码(原理)读后感

FusionBin
FusionBin
Jul 10, 2017 · 3 min read

Redux是个非常优秀的框架,特别是在与复杂 React 应用配合使用的时候它的优势体现得更突出。

Redux 是一个状态管理器,是一个思想很重,而代码很轻的框架。API 也非常简单,列出如下:

createStore(reducer, [preloadedState], enhancer)
combineReducers(reducers)
applyMiddleware(...middlewares)
bindActionCreators(actionCreators, dispatch)
compose(...functions)

createStore 方法

createStore 返回一个Store实例。Store是个普通的 JavaScript 对象,里面包含几个方法:

getState()
dispatch(action)
subscribe(listener)
replaceReducer(nextReducer)

getState 返回 Store 当前的状态树,它与 Store 最后一个 reducer 的返回值相同。

dispatch 是唯一可以改变状态的方法。通过触发相应的 action 来达到改变 state 的目的。dispatch 会

subscribe 是添加 state 改变后的回调函数的方法,返回一个取消监听的函数。

redux createStore 图示

applyMiddleware 方法

applyMiddleware 是与 createStore 配合使用的, applyMiddleware(…middlewares) 应用之后返回的正是 createStore 的第三个参数 endhancer 。

middleware 与 express 或 koa 等框架的中间件是类似的,也是函数式编程里 Monad 思想的一个应用。每个 middleware 中间件做的事件只是定制化 dispatch,并把改造过后的 dispatch(即 `next` 参数)传给后继的中间件。中间件的书写有规定的形式,其形式如下:

const myMiddleware = (store) => (next) => (action) => {
// 具体逻辑
// 但,这里必须执行 next, 也就是上一个 dispatch(action)
// 以保证各个 middleware 中间件的执行
}

middleware的第一层,即传入 store 是为了拿到原始的 dispatch 方法,第二层是为了实现链式调用。

关于 applyMiddleware 的具体实现逻辑可以参考这篇文章。要而反过来看推导过程可以看redux官方文档

剩余的几个API比较简单,就不展开了。

总结一下,redux 的实现是一个典型的函数式编程案例。单纯作为函数式编程范例来看也是不错的。不过redux的意义远远不止如此,这的思想才是关键。

FusionBin

Written by

FusionBin

野生前端攻城狮

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade