Redux源码解读

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

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

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

Redux源码解读_第1张图片
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源码解读)