今天向大家簡單介紹下Redux源碼,若有理解差誤,歡迎在下面留言~
Redux源碼地址:https://github.com/reactjs/redux/tree/master/src
大家可以看到Redux目錄結(jié)構(gòu)為
我們只介紹最重要的一個文件夾createStore.js
import isPlainObject from 'lodash/isPlainObject'
import $$observable from 'symbol-observable'
export const ActionTypes = {
INIT: '@@redux/INIT' //這就是當你在創(chuàng)建一個store時,最開始的action.type值
}
/*
參數(shù)reducer就是你傳入的要更改state的函數(shù)
參數(shù)preloadedState是可選參數(shù)知给,指初始state
參數(shù)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
}
/*
參數(shù)listener是一個監(jiān)聽函數(shù)
返回值為一個取消監(jiān)聽的函數(shù)
*/
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected listener to be a function.')
}
let isSubscribed = true
ensureCanMutateNextListeners()
nextListeners.push(listener) // 添加在監(jiān)聽數(shù)組中
return function unsubscribe() {
if (!isSubscribed) {
return
}
isSubscribed = false
ensureCanMutateNextListeners()
const index = nextListeners.indexOf(listener)
nextListeners.splice(index, 1)
}
}
/*
參數(shù)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
//現(xiàn)在的currentReducer就是你傳入的reducer,執(zhí)行這個函數(shù)對state進行更新砚偶,返回給當前的currentState。
currentState = currentReducer(currentState, action)
} finally {
isDispatching = false
}
//遍歷出當前所有的監(jiān)聽洒闸,并依次執(zhí)行染坯。
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)函數(shù)時丘逸,會返回四個方法供我們使用单鹿。當用戶在view層進行數(shù)據(jù)操作時,這時就有相應的action產(chǎn)生深纲,使用store.dispatch(action)來執(zhí)行reducer函數(shù)對state進行更新仲锄,這樣通過getState()就可以獲取最新的state在組件中進行動態(tài)顯示。
大家可以通過官網(wǎng)上的Counter實例驗證一下湃鹊。
代碼地址:https://github.com/reactjs/redux/tree/master/examples/counter