Redux源码解读

今天向大家简单介绍下Redux源码,若有理解差误,欢迎在下面留言~

Redux源码地址:https://github.com/reactjs/redux/tree/master/src

大家可以看到Redux目录结构为

redux.png

我们只介绍最重要的一个文件夹createStore.js


import isPlainObject from 'lodash/isPlainObject'
import $$observable from 'symbol-observable'


export const ActionTypes = {

INIT: '@@redux/INIT'   //这就是当你在创建一个store时,最开始的action.type值

}

/*
参数reducer就是你传入的要更改state的函数
参数preloadedState是可选参数,指初始state
参数enhancer也是可选,一般不用
*/
export default function createStore(reducer, preloadedState, enhancer) {

if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {

enhancer = preloadedState

preloadedState = undefined

}

if (typeof enhancer !== 'undefined') {

if (typeof enhancer !== 'function') {

throw new Error('Expected the enhancer to be a function.')

}

return enhancer(createStore)(reducer, preloadedState)

}

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) {

nextListeners = currentListeners.slice()

}

}

//得到当前的state值
function getState() {

return currentState

}

/*
参数listener是一个监听函数
返回值为一个取消监听的函数
*/
function subscribe(listener) {

if (typeof listener !== 'function') {

throw new Error('Expected listener to be a function.')

}

let isSubscribed = true

ensureCanMutateNextListeners()

nextListeners.push(listener) // 添加在监听数组中

return function unsubscribe() {

if (!isSubscribed) {

return

}

isSubscribed = false

ensureCanMutateNextListeners()

const index = nextListeners.indexOf(listener)

nextListeners.splice(index, 1)

}

}

/*
参数action为你传入的用户进行的操作对象
*/
function dispatch(action) {

if (!isPlainObject(action)) {

throw new Error(

'Actions must be plain objects. ' +

'Use custom middleware for async actions.'

)

}

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

//现在的currentReducer就是你传入的reducer,执行这个函数对state进行更新,返回给当前的currentState。
currentState = currentReducer(currentState, action)

} finally {

isDispatching = false

}
//遍历出当前所有的监听,并依次执行。
const listeners = currentListeners = nextListeners

for (let i = 0; i < listeners.length; i++) {

const listener = listeners[i]

listener()

}

return action

}

/**

 * Replaces the reducer currently used by the store to calculate the state.

 *

 * You might need this if your app implements code splitting and you want to

 * load some of the reducers dynamically. You might also need this if you

 * implement a hot reloading mechanism for Redux.

 *

 * @param {Function} nextReducer The reducer for the store to use instead.

 * @returns {void}

 */

function replaceReducer(nextReducer) {

if (typeof nextReducer !== 'function') {

throw new Error('Expected the nextReducer to be a function.')

}

currentReducer = nextReducer

dispatch({ type: ActionTypes.INIT })

}

/**

 * Interoperability point for observable/reactive libraries.

 * @returns {observable} A minimal observable of state changes.

 * For more information, see the observable proposal:

 * https://github.com/zenparsing/es-observable

 */

function observable() {

const outerSubscribe = subscribe

return {

/**

 * The minimal observable subscription method.

 * @param {Object} observer Any object that can be used as an observer.

 * The observer object should have a `next` method.

 * @returns {subscription} An object with an `unsubscribe` method that can

 * be used to unsubscribe the observable from the store, and prevent further

 * emission of values from the observable.

 */

subscribe(observer) {

if (typeof observer !== 'object') {

throw new TypeError('Expected the observer to be an object.')

}

function observeState() {

if (observer.next) {

observer.next(getState())

}

}

observeState()

const unsubscribe = outerSubscribe(observeState)

return { unsubscribe }

},

[$$observable]() {

return this

}

}

}


//初始化时的action
dispatch({ type: ActionTypes.INIT })

//返回四个方法,分别完成相应的功能
return {

    dispatch,
    subscribe,
    getState,
    replaceReducer,
    [$$observable]: observable
}
}

当我们使用createStore(reducer)函数时,会返回四个方法供我们使用。当用户在view层进行数据操作时,这时就有相应的action产生,使用store.dispatch(action)来执行reducer函数对state进行更新,这样通过getState()就可以获取最新的state在组件中进行动态显示。

大家可以通过官网上的Counter实例验证一下。

代码地址:https://github.com/reactjs/redux/tree/master/examples/counter

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 redux并不局限于flux与react。redux 自身保持简洁以便适配各种场景,让社区发展出各种 red...
    yeatszhang阅读 731评论 0 49
  • http://gaearon.github.io/redux/index.html ,文档在 http://rac...
    jacobbubu阅读 80,064评论 35 198
  • "react-redux": "^5.0.6" redux和react之间的桥梁是react的context,re...
    别过经年阅读 759评论 0 1
  • 一、CMS管理系统功能 CMS是ContentManagementSystem的缩写,意为"内容管理系统"。 CM...
    默默先生Alec阅读 5,414评论 0 7
  • 原来喜欢一个人是这样的感觉。 我从不知道。 思念、心焦、和欣喜若狂。 然而有一天,我的世界变成了无穷无尽的黑暗, ...
    ouenglli阅读 196评论 0 0