Redux 源码实现

// 判断是否为纯对象
function isPlainObject(obj) {
  if (typeof obj !== 'object' || obj === null) return false
  let proto = obj
  while (Object.getPrototypeOf(proto)) {
    proto = Object.getPrototypeOf(proto)
  }
  return Object.getPrototypeOf(obj) === proto
}
function createStore(reducer, initState) {
  if (typeof reducer !== 'function') {
    throw new Error('reducer必须是一个函数')
  }
  let currentReducer = reducer
  let currentState = initState
  let currentListeners = []
  function despatch(action) {
    if (!isPlainObject(action)) {
      throw new Error('action 必须事一个纯对象')
    }
    if (typeof action.type === 'undefined') {
      throw new Error('action type 属性不能是 undefined')
    }
    currentState = currentReducer(currentState, action)
    currentListeners.forEach(it => it())
    return action
  }
  function subscribe(cb) {
    let flag = true
    currentListeners.push(cb)
    return () => {
      if (!flag) return
      const index = currentListeners.findIndex(it => it === cb)
      currentListeners.splice(index, 1)
      flag = false
    }
  }
  function getState() {
    return currentState
  }
  dispatch({ type: '@@redux/INIT' })
  return {
    getState,
    subscribe,
    despatch
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。