这篇文章会很长。redux源码读起来并不困难。读懂redux的源码有利于更好的使用redux。
但是react-redux复杂多。所以分阶段写。
redux源码分析
在使用redux中,比较重要的三个函数: createStore
,store.dispatch
,reducer
。其中有一个比较难以理解的点是,为什么reducer每次都要返回一个新的变量。我们先来分析 createStore
函数。
redux整个设计遵循的是订阅-更新模式。
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
的中的变量。也是存储整个工程的state数据的变量。
- dispatch函数
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
函数可以看到reducer的设计思想。currentReducer
是我们调用createStore
时传递进来的reducer函数。一般reducer
函数是这样定义的:
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的数据格式一般是这样的:
{
type: types.SEND_GOODS,
response: response
}
连在一起看语句currentState = currentReducer(currentState, action)
是不是好懂很多呢?将保存在store上的state传入reducer
函数中,获得新的state
(要复制一份state的原因还不清楚)
接下来
const listeners = (currentListeners = nextListeners)
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i]
listener()
}
那么currentListeners
何时更新?我们接着看一下subscribe
函数。
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)
}
}
执行subscribe
函数,实际上就是将回调函数加入nextListeners
这个list中,当执行dispatch
时,nextListeners
中每个listener函数会顺序执行。这样就完成了每次store中数据发生变更,subscribe
中函数就会执行一次。至于为什么会有两个变量currentListeners
和nextListeners
来维持回调队列,还不是很清楚原因。
最后提出三个问题:
- 为什么reduce函数中中要返回新的state
- 为什么listener也要保持纯净
- 为什么react中这么喜欢使用mutual哲学
后续更新:
- observable 由于没有用过
observable
,这部分的源码先不看。
react-redux源码分析
- 如何感知store的变化
- 如何修改state的变化