這篇文章會(huì)很長(zhǎng)衫画。redux源碼讀起來(lái)并不困難睡榆。讀懂redux的源碼有利于更好的使用redux。
但是react-redux復(fù)雜多缠导。所以分階段寫廉羔。
redux源碼分析
在使用redux中,比較重要的三個(gè)函數(shù): createStore
,store.dispatch
,reducer
酬核。其中有一個(gè)比較難以理解的點(diǎn)是,為什么reducer每次都要返回一個(gè)新的變量蜜另。我們先來(lái)分析 createStore
函數(shù)。
redux整個(gè)設(shè)計(jì)遵循的是訂閱-更新模式嫡意。
export default function createStore(reducer, preloadedState, enhancer) {
let currentReducer = reducer
let currentState = preloadedState
let currentListeners = []
let nextListeners = currentListeners
let isDispatching = false
function getState() {
if (isDispatching) {
throw new Error(
'You may not call store.getState() while the reducer is executing. ' +
'The reducer has already received the state as an argument. ' +
'Pass it down from the top reducer instead of reading it from the store.'
)
}
return currentState
}
}
其中举瑰,currentState
是維持在createStore
的中的變量。也是存儲(chǔ)整個(gè)工程的state數(shù)據(jù)的變量蔬螟。
- dispatch函數(shù)
function dispatch(action) {
...
if (isDispatching) {
throw new Error('Reducers may not dispatch actions.')
}
try {
isDispatching = true
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
}
dispatch
函數(shù)可以看到reducer的設(shè)計(jì)思想此迅。currentReducer
是我們調(diào)用createStore
時(shí)傳遞進(jìn)來(lái)的reducer函數(shù)。一般reducer
函數(shù)是這樣定義的:
const reducers = (state = initialState, action) => {
let newState = Object.assign({}, state);
switch (action.type) {
case types.GET_ORDERS:
newState.orderInfo = action.response;
case types.GET_GOODS:
newState.goodsInfo = action.response;
case types.SET_ALL_EXPRESS_COMPANY:
newState.expressCompany = action.response;
case types.SET_EXPRESS_COMPANY:
newState.expressInfo = {
trackingNumber: state.expressInfo.trackingNumber,
shippingId: action.response.shippingId,
shippingName: action.response.shippingName,
}
case types.SET_EXPRESS_STATUS:
newState.showExpressSuccessModal = action.response;
case types.INIT_TRACK_NUMBER:
newState.expressInfo = {
trackingNumber: action.response,
shippingId: state.expressInfo.shippingId,
shippingName: state.expressInfo.shippingName,
}
}
return newState
}
export default reducers
而action的數(shù)據(jù)格式一般是這樣的:
{
type: types.SEND_GOODS,
response: response
}
連在一起看語(yǔ)句currentState = currentReducer(currentState, action)
是不是好懂很多呢旧巾?將保存在store上的state傳入reducer
函數(shù)中耸序,獲得新的state
(要復(fù)制一份state的原因還不清楚)
接下來(lái)
const listeners = (currentListeners = nextListeners)
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i]
listener()
}
那么currentListeners
何時(shí)更新?我們接著看一下subscribe
函數(shù)鲁猩。
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected the listener to be a function.')
}
if (isDispatching) {
throw new Error(
'You may not call store.subscribe() while the reducer is executing. ' +
'If you would like to be notified after the store has been updated, subscribe from a ' +
'component and invoke store.getState() in the callback to access the latest state. ' +
'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'
)
}
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)
}
}
執(zhí)行subscribe
函數(shù)坎怪,實(shí)際上就是將回調(diào)函數(shù)加入nextListeners
這個(gè)list中,當(dāng)執(zhí)行dispatch
時(shí)廓握,nextListeners
中每個(gè)listener函數(shù)會(huì)順序執(zhí)行搅窿。這樣就完成了每次store中數(shù)據(jù)發(fā)生變更,subscribe
中函數(shù)就會(huì)執(zhí)行一次。至于為什么會(huì)有兩個(gè)變量currentListeners
和nextListeners
來(lái)維持回調(diào)隊(duì)列隙券,還不是很清楚原因男应。
最后提出三個(gè)問(wèn)題:
- 為什么reduce函數(shù)中中要返回新的state
- 為什么listener也要保持純凈
- 為什么react中這么喜歡使用mutual哲學(xué)
后續(xù)更新:
- observable 由于沒有用過(guò)
observable
,這部分的源碼先不看。
react-redux源碼分析
- 如何感知store的變化
- 如何修改state的變化