入口文件index.js
import createStore from './createStore'
import combineReducers from './combineReducers'
import bindActionCreators from './bindActionCreators'
import applyMiddleware from './applyMiddleware'
import compose from './compose'
import warning from './utils/warning'
import __DO_NOT_USE__ActionTypes from './utils/actionTypes'
/*
* 判断如果不是production模式下,isCrushed函数名被编译 则warning
*/
function isCrushed() {}
if (
process.env.NODE_ENV !== 'production' &&
typeof isCrushed.name === 'string' &&
isCrushed.name !== 'isCrushed'
) {
warning(
'You are currently using minified code outside of NODE_ENV === "production". ' +
'This means that you are running a slower development build of Redux. ' +
'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' +
'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' +
'to ensure you have the correct code for your production build.'
)
}
export {
createStore,
combineReducers,
bindActionCreators,
applyMiddleware,
compose,
__DO_NOT_USE__ActionTypes
}
入口文件很简单,就是把几个常用的api暴露的出来
那么接下来就从最熟悉的createStore入手
createStore.js
这里我把注释给删掉了 有兴趣的小伙伴可以看一下,还是很有帮助的
判断入参类型
// 判断入参类型
if (
(typeof preloadedState === 'function' && typeof enhancer === 'function') ||
(typeof enhancer === 'function' && typeof arguments[3] === 'function')
) {
throw new Error(
'It looks like you are passing several store enhancers to ' +
'createStore(). This is not supported. Instead, compose them ' +
'together to a single function.'
)
}
// 交换入参,适配写法createStore(reducer, enhancer)
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
enhancer = preloadedState
preloadedState = undefined
}
// enhancer为function
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.')
}
return enhancer(createStore)(reducer, preloadedState) // 这里可以先记下来
}
// reducer为function
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.')
}
可以看到这里主要是容错逻辑 其中
return enhancer(createStore)(reducer, preloadedState)
这里可以先忽略一下可以先接着往下看
声明所需变量
// 接收传入的reducer
let currentReducer = reducer
// 接收传入的initState
let currentState = preloadedState
// 监听函数队列
let currentListeners = []
// 浅拷贝监听函数队列
let nextListeners = currentListeners
// dispatching 开关 应该是为了保持数据的一致性和行为的隔离
let isDispatching = false
这里可以看到声明了一些变量,很容易想到观察者模式,和单一模式
函数 ensureCanMutateNextListeners
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice()
}
}
字面意思 确保可变的listeners 是一个工具函数 对listeners进行了 slice操作(一层深拷贝)
函数 getState
function getState() {
if (isDispatching) {
throw new Error(
'当reducer执行时. 不能调用store.getState. ' +
'reducer已经接收参数作为state. ' +
'在reducer中处理,而不是从getState读取'
)
}
return currentState
}
读取state函数,其中容错逻辑是正在dispatching时不能调用getState,应该是为了保证数据的一致性,不过看完redux源码之后可以看到dispatch是同步的,且一致的,这里的一致性和同 步性指 的是在reducer处理参数开始到reducer处理结束,中间没有任何其他作用域干扰(reducer应该为一个纯函数),
函数subscribe
function subscribe(listener) {
// listener应该为一个callback
if (typeof listener !== 'function') {
throw new Error('Expected the listener to be a function.')
}
// 容错逻辑 不能再dispatching时 执行subscribe
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#subscribelistener for more details.'
)
}
// 标识成功订阅
let isSubscribed = true
// 确保listeners 队列隔离性
ensureCanMutateNextListeners()
// 把callback加入到监听队列
nextListeners.push(listener)
return function unsubscribe() {
/*
利于闭包进行容错处理
即如果 上边的listener不为function 正在dispatching时调用subscribe 则返回的unsubscribe函数直接return
*/
if (!isSubscribed) {
return
}
// 容错逻辑
if (isDispatching) {
throw new Error(
'You may not unsubscribe from a store listener while the reducer is executing. ' +
'See https://redux.js.org/api-reference/store#subscribelistener for more details.'
)
}
// 标识取消订阅,即如果多次调用unsubscribe 只有第一次执行生效
isSubscribed = false
// 确保listeners队列隔离性
ensureCanMutateNextListeners()
// 利于闭包的特性 找到订阅时传入的callback
const index = nextListeners.indexOf(listener)
// 删除callback
nextListeners.splice(index, 1)
// 把currentListeners置为null 保持数据的一致性 在下边dispatch可以找到答案
currentListeners = null
}
}
可以看到这是一个订阅函数 返回一个去掉订阅的函数
1.利用的闭包原理 完成了如果传入callback不为function 、正在dispatching下调用subscribe 情况下 取消订阅不生效 和多次调用返回的unsubscribe只有只有第一次生效的容错处处理(isSubscribed 变量)
2.利用闭包在返回的取消订阅函数中拿到 订阅的callback
3.保证监听队列callback的隔离性和一致性
函数dispatch
function dispatch(action) {
if (!isPlainObject(action)) {
throw new Error(
'action 应该为一个简单的object' +
'使用自定义中间件处理异步action.'
)
}
if (typeof action.type === 'undefined') {
throw new Error(
'action必须有一个type属性' +
'是否拼错?'
)
}
if (isDispatching) {
throw new Error('reducer正在处理不能dispatch.')
}
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函数,为什么说最原始的呢,谜底在中间件,我们先看一下这个dispatch
1.判断传入的action是否为一个简单的object 这里使用到的一个 isPlainObject 函数
export default function isPlainObject(obj) {
/*
判断入参如果不为object直接返回false
*/
if (typeof obj !== 'object' || obj === null) return false
/*
判断object是否为简单对象
即字面量创建 const obj = {}
构造函数创建 const obj = new Object()
object.create创建 const obj = Object.create(Object.prototype)
创建的
原理:
以上三种方法都直接继承Object构造函数
即 obj.__proto__ === Object.prototype =true
Object.prototype.__proto__ === null =true
即while循环执行一次 这时
proto === Object.prototype =true
Object.getPrototypeOf(proto) === null
*/
let proto = obj
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto)
}
return Object.getPrototypeOf(obj) === proto
}
2.action的type为必传
3.判断是否正在dispatching可以理解为容错逻辑
try {
isDispatching = true
currentState = currentReducer(currentState, action)
} finally {
isDispatching = false
}
调用reducer 传入action 返回新的state
const listeners = (currentListeners = nextListeners)
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i]
listener()
}
依次调用调用监听队列
函数observable
function observable() {
const outerSubscribe = subscribe
return {
subscribe(observer) {
if (typeof observer !== 'object' || observer === null) {
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
}
}
}
这个api并没有直接暴露给开发者
到这里createStore已经看完了,但是
之前遗留的一个问题 当传入enhancer时(applyMiddleware)时,调用了enhancer传入了createStore自身,又传入了reducer和preloadedState
applyMiddleware.js(redux强大的奥秘)
/**
* 创建redux的store,将中间件应用到dispatch
*
* 对各种任务表达都很方便
*
* 查看redux-thunk 作为示例
*
* 因为中间件可能是异步的,所以应该放在第一个
*
* 每个中间件都将被赋予getState dispatch作为参数
* @param {...Function} 要应用的中间链 .
* @returns {Function} 一个加强的store.
*/
export default function applyMiddleware(...middlewares) {
return createStore => (...args) => {
const store = createStore(...args)
let dispatch = () => {
throw new Error(
'dispatch在初始化的时候不能于调度. ' +
'其他中间件不应该使用这个dispatch.'
)
}
const middlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
}
const chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
我们逐行分析:
接收中间件函数,返回一个接收createStore 和args(reducer, preloadedState)的链式函数 调用createStore 传入reducer和preloadedState
初始化dispatch,此时的dispatch处于初始化状态 调用的话会error, 声明一个对象 getstate为store的getstate dispatch为上边声明的dispatch
map传入的middlewares数组并调用 传入刚才声明的对象
(重点)
使用compose函数,扩展传入map调用后的middlewares
compose
export default function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg
}
if (funcs.length === 1) {
return funcs[0]
}
return funcs.reduce((a, b) => (...args) => a(b(...args)))
}
reset 参数为一个数组,使用数组的reduce方法生成了一个复合函数(看不太明白的可以先研究一下数组的reducer方法)
此时的复合函数可以理解为 接收一个参数 调用function b 返回值为参数再调用函数a
接下来调用复合函数 传入createStore 返回的原始dispatch
把返回值重新赋值给刚才声明报error的dispatch
返回一个对象 扩展了原始的store,加强版的dispatch覆盖了 原始的dispatch 即使用applymiddleware后 开发者拿到的dispatch都是加强版的
说到这里可能有点懵逼 不过不急 在最后会把 compose函数做了什么 以及为什么这样写说明白 我们先继续往下看
combineReducers.js
/**
* 将值为不同的reducer函数转换为单个reducer函数
* 调用每一个子reducer并收集结果
* 转换为单个状态对象,他的键对应传入的键
*/
export default function combineReducers(reducers) {
const reducerKeys = Object.keys(reducers)
const finalReducers = {}
for (let i = 0; i < reducerKeys.length; i++) {
const key = reducerKeys[i]
if (process.env.NODE_ENV !== 'production') {
if (typeof reducers[key] === 'undefined') {
warning(`No reducer provided for key "${key}"`)
}
}
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key]
}
}
const finalReducerKeys = Object.keys(finalReducers)
/*
拿到值为function的reducer
*/
let unexpectedKeyCache
if (process.env.NODE_ENV !== 'production') {
unexpectedKeyCache = {}
}
let shapeAssertionError
try {
assertReducerShape(finalReducers)
} catch (e) {
shapeAssertionError = e
}
return function combination(state = {}, action) {
if (shapeAssertionError) {
throw shapeAssertionError
}
if (process.env.NODE_ENV !== 'production') {
const warningMessage = getUnexpectedStateShapeWarningMessage(
state,
finalReducers,
action,
unexpectedKeyCache
)
if (warningMessage) {
warning(warningMessage)
}
}
let hasChanged = false
const nextState = {}
for (let i = 0; i < finalReducerKeys.length; i++) {
const key = finalReducerKeys[i]
const reducer = finalReducers[key]
const previousStateForKey = state[key]
const nextStateForKey = reducer(previousStateForKey, action)
if (typeof nextStateForKey === 'undefined') {
const errorMessage = getUndefinedStateErrorMessage(key, action)
throw new Error(errorMessage)
}
nextState[key] = nextStateForKey
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
hasChanged =
hasChanged || finalReducerKeys.length !== Object.keys(state).length
return hasChanged ? nextState : state
}
}
combineReducers函数把多个reducer函数组合成一个复合reducer 并返回一个组合的state,在之前的createStore 的dispatch中可以看到 在dispatch时并么有去做区分
第一段代码
清晰明了 拿到值为function的reducers 如果是开发环境下 存在值为undefined的reducer 则报warning
第二段代码
这里使用到了一个assertReducerShape 函数
/*
确保初始化/和接收到未知type的时候 reducer正常返回
*/
function assertReducerShape(reducers) {
Object.keys(reducers).forEach(key => {
const reducer = reducers[key]
const initialState = reducer(undefined, { type: ActionTypes.INIT })
if (typeof initialState === 'undefined') {
throw new Error(
`Reducer "${key}" returned undefined during initialization. ` +
`If the state passed to the reducer is undefined, you must ` +
`explicitly return the initial state. The initial state may ` +
`not be undefined. If you don't want to set a value for this reducer, ` +
`you can use null instead of undefined.`
)
}
if (
typeof reducer(undefined, {
type: ActionTypes.PROBE_UNKNOWN_ACTION()
}) === 'undefined'
) {
throw new Error(
`Reducer "${key}" returned undefined when probed with a random type. ` +
`Don't try to handle ${ActionTypes.INIT} or other actions in "redux/*" ` +
`namespace. They are considered private. Instead, you must return the ` +
`current state for any unknown actions, unless it is undefined, ` +
`in which case you must return the initial state, regardless of the ` +
`action type. The initial state may not be undefined, but can be null.`
)
}
})
}
对于每一个reducer都使用initType 和随机type 调用 如果返回值为undefined 则warning
返回一个结合函数
首先是容错代码
第一个就是刚才的throw 如果存在 则直接报错
第二个是判断state是否是一个简单对象 和 是否state存在 有reducers不存在的key
getUnexpectedStateShapeWarningMessage 函数
function getUnexpectedStateShapeWarningMessage(
inputState,
reducers,
action,
unexpectedKeyCache
) {
const reducerKeys = Object.keys(reducers)
const argumentName =
action && action.type === ActionTypes.INIT
? 'preloadedState argument passed to createStore'
: 'previous state received by the reducer'
if (reducerKeys.length === 0) {
return (
'store 没有一个有效的reducer 确保传递给combineReducers 的参数是一个值为reducer的对象'
)
}
// 判断state是否为一个简单的对象
if (!isPlainObject(inputState)) {
return (
`The ${argumentName} has unexpected type of "` +
{}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] +
`". Expected argument to be an object with the following ` +
`keys: "${reducerKeys.join('", "')}"`
)
}
/*
判断state是否存在reducers不存在的key
*/
const unexpectedKeys = Object.keys(inputState).filter(
key => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]
)
unexpectedKeys.forEach(key => {
unexpectedKeyCache[key] = true
})
if (action && action.type === ActionTypes.REPLACE) return
if (unexpectedKeys.length > 0) {
return (
`Unexpected ${unexpectedKeys.length > 1 ? 'keys' : 'key'} ` +
`"${unexpectedKeys.join('", "')}" found in ${argumentName}. ` +
`Expected to find one of the known reducer keys instead: ` +
`"${reducerKeys.join('", "')}". Unexpected keys will be ignored.`
)
}
}
这里就不说了 核心就是这两行代码
const unexpectedKeys = Object.keys(inputState).filter(
key => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]
)
剩下的就是reducer触发逻辑了
// 初始化change为false
let hasChanged = false
const nextState = {}
// 循环reducers的key
for (let i = 0; i < finalReducerKeys.length; i++) {
const key = finalReducerKeys[i]
const reducer = finalReducers[key]
// 拿到旧的state
const previousStateForKey = state[key]
// reducer返回的新state
const nextStateForKey = reducer(previousStateForKey, action)
// 如果nextState为undefined 则error
if (typeof nextStateForKey === 'undefined') {
const errorMessage = getUndefinedStateErrorMessage(key, action)
throw new Error(errorMessage)
}
// 合并state
nextState[key] = nextStateForKey
// 如果olderState 不等于newState 则change为true
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
// 如果state没有更改 但是state和reducers 的key有所更改也为change
hasChanged =
hasChanged || finalReducerKeys.length !== Object.keys(state).length
// 返回state
return hasChanged ? nextState : state
除了这些可以说可以说必用的api外 还有一个函数也是蛮常用的
bindActionCreators.js
最常见的用法莫过于这种方式 配合react-redux 的connect 第二个参数mapDispatchToProps使用
下边是他的源码,其实就是做了一层转换处理
export default function bindActionCreators(actionCreators, dispatch)
// 如果传入的是一个actionCreator 直接转换
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch)
}
// 如果不是一个function和object 或者为null 则error
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error(
`bindActionCreators expected an object or a function, instead received ${
actionCreators === null ? 'null' : typeof actionCreators
}. ` +
`Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
)
}
// 遍历转化
const boundActionCreators = {}
for (const key in actionCreators) {
const actionCreator = actionCreators[key]
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
}
}
return boundActionCreators
}
// 返回一个function 闭包保存了dispatch 和actionCreator
function bindActionCreator(actionCreator, dispatch) {
return function() {
return dispatch(actionCreator.apply(this, arguments))
}
}
到此为止redux的源码就看完了
接下来分析一下之前遗留的问题 就是中间件实现机制和运行流程
redux中间件的实现 及运行流程
其实最让人迷惑的无非就是这几行代码
此时我们可以结合一下redux-thunk的源码来解读一下
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => {
return next=> {
return action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
}
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
redux-thunk的源码就这么多 是的 就这么多
首先我们先分析一下 能理解到的
1.map 的时候调用了中间件,并传入了一个具有getState和dispatch的对象,dispatch对象初始化之后被重新赋予了加强之后的dispatch
那么 可以想到
这里的dispatch就是上边的dispatch
接着往下看
dispatch = compose(...chain)(store.dispatch)
这行代码我们拆成这样的
dispatch = compose(...chain)
dispatch = dispatch(store.dispatch)
先来分析compose (0的情况就不说了)
export default function compose(...funcs) {
if (funcs.length === 1) {
return funcs[0]
}
return funcs.reduce((a, b) => (...args) => a(b(...args)))
}
先从简单的来 如果中间件的个数为1那么直接返回这个中间件 以redux-thunk为例 即返回了
划红线的部分(上一层的参数dispatch,getState因为闭包的原因已经保存了下来)
接下往下
dispatch = dispatch(store.dispatch)
调用了划红线的部分传入了store的dispatch(原始的dispatch)
那么此时返回的部分就是这样了
然后把返回值赋予了dispatch(加强版)
那么此时thunk函数就成了这样
此时里边的剩下两行代码也很好理解了 那么触发dispatch的流程应该是这样的
验证:那么如果使用redux-thunk传入个function 那么应该会调用两次redux-thunk
接下来看一下多个中间件的情况
在此我模拟了一下多个中间件的情况
const a = (store) =>{
console.log('a:', store)
return (next)=> {
console.log('a:',next)
return (action) => {
console.log('a:',action)
return next(action)
}
}
}
const b = (store) =>{
console.log('b:', store)
return (next)=> {
console.log('b:',next)
return (action) => {
console.log('b:',action)
return next(action)
}
}
}
const composeFunc = (...funs) => {
return funs.reduce((a, b) => {
return (...args) => a(b(...args))
})
}
const middleWare = [a, b].map(item => item('store'))
console.log(composeFunc(a, b),'---composeFunc(a, b)')
const reinforce = composeFunc(a, b)('store.dispatch');
console.log(reinforce.toString())
此时最后拿到的dispatch是
而此时a函数的next是
b函数的next则是最原始的dispatch
流程大致是这样的
到这里redux的分析接结束了 其实并不是特别难,但是设计思想很牛皮,特别是中间件的设计
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!