Redux源码(一) —— index.js

Preface

现在都9012了,还谈redux源码,是不是太晚了?回答是,但又不是,毕竟不写出来只会是更晚。

当前版本为redux@4.0.1,可能会根据版本不同存在些许差异,不过不影响。

Directory

src
|---- utils
|    |---- actionTypes.js
|    |---- isPlainObject.js
|    |---- warning.js
|---- applyMiddle.js
|---- bindActionCreator.js
|---- combineReducers.js
|---- compose.js
|---- createStore.js
|---- index.js

Analysis

utils

actionTypes.js

actionTypes.js保存了redux中的一些私有action类型,根据名称也很好理解,这里就不过多赘述了。

const randomString = () =>
  Math.random()
    .toString(36)
    .substring(7)
    .split('')
    .join('.')

const ActionTypes = {
  INIT: `@@redux/INIT${randomString()}`,
  REPLACE: `@@redux/REPLACE${randomString()}`,
  PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
}
export default ActionTypes

isPlainObject.js

isPlainObject.js用于判断是否是一个简单对象,这里简单的意思是指是否是单纯的object,如数组、函数等就不是,主要依靠的是Object.getPrototypeOf获取当前对象的原型,通过当前对象的直接原型和最终原型(即object)相比较判断是否是简单对象。

export default function isPlainObject(obj) {
  if (typeof obj !== 'object' || obj === null) return false

  let proto = obj
  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto)
  }

  return Object.getPrototypeOf(obj) === proto
}

warning.js

warning.js用于提供一个显示警告信息的通用方法,接受一条错误信息,如果支持console.error则会先使用这条命令打印警告信息,再抛出一个Error,不过会在方法中被catch掉,没有其他操作。

export default function warning(message) {
  if (typeof console !== 'undefined' && typeof console.error === 'function') {
    console.error(message)
  }
  try {
    throw new Error(message)
  } catch (e) {}
}

index.js

index.js是redux的入口文件,主要负责判断当前是否是正确的生产环境版本,以及最主要的:向用户提供api,如基本的createStore就是在这里导出给用户的。

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'

// ... 此处省略了判断环境以及版本的警告提示

export {
  createStore,
  combineReducers,
  bindActionCreators,
  applyMiddleware,
  compose,
  __DO_NOT_USE__ActionTypes
}

All

index
compose
applyMiddleware
bindActionCreators
combineReducers
createStore

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,281评论 0 3
  • 写在开头 前置知识内容,react、react-redux。 react-redux文档:https://www....
    前端开发爱好者阅读 389评论 0 0
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,135评论 1 32
  • 前端开发面试题 面试题目: 根据你的等级和职位的变化,入门级到专家级,广度和深度都会有所增加。 题目类型: 理论知...
    怡宝丶阅读 2,605评论 0 7
  • error code(错误代码)=0是操作成功完成。error code(错误代码)=1是功能错误。error c...
    Heikki_阅读 3,426评论 1 9