一、Redux是什么?
众所周知,Redux最早运用于React框架中,是一个全局状态管理器。Redux解决了在开发过程中数据无限层层传递而引发的一系列问题,因此我们有必要来了解一下Redux到底是如何实现的?
二、Redux的核心思想?
Redux主要分为几个部分:dispatch、reducer、state。
我们着重看下dispatch,该方法是Redux流程的第一步,在用户界面中通过执行dispatch,传入相对应的action对象参数,action是一个描述类型的对象,紧接着执行reducer,最后整体返回一个store对象,我们来看下这部分的源码:
// 主函数createStore
// 返回一个store对象
export default function createStore(reducer, preloadedState, enhancer) {
// 增强器
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
// 获取最终的state
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
}
// dispatch
// 参数action
function dispatch(action) {
// 校验传入的action
// action必须是个对象,否则抛出错误信息
if (!isPlainObject(action)) {
throw new Error(
'Actions must be plain objects. ' +
'Use custom middleware for async actions.'
)
}
// 检验action对象的必要属性
// type属性是action对象必要的属性
// 如果传入的action没有type属性,则抛出错误信息
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
// 执行传入的reducer函数
// 返回state,给currentState赋值
currentState = currentReducer(currentState, action)
} finally {
// 一个dispatch执行完,还原状态
isDispatching = false
}
// 执行订阅函数队列
// dispatch执行的同时会一并执行订阅队列
const listeners = (currentListeners = nextListeners)
for (let i = 0; i <