Redux源码分析之createStore

小编 2026-06-05 阅读:1337 评论:0
Redux源码分析之基本概念Redux源码分析之createStoreRedux源码分析之bin...

Redux源码分析之基本概念

Redux源码分析之createStore

Redux源码分析之bindActionCreators

Redux源码分析之combineReducers

Redux源码分析之compose

 Redux源码分析之applyMiddleware 

 

接着前面的,我们继续,打开createStore.js, 直接看最后, createStore返回的就是一个带着5个方法的对象。

  return {    dispatch,    subscribe,    getState,    replaceReducer,    [$$observable]: observable  }

 同样的,我先删除一些不需要的代码,简化成如下, 注意看备注。(注:这里先无视中间件和enhancer,后篇再说)

export const ActionTypes = {    INIT: '@@redux/INIT'}export default function createStore(reducer, preloadedState, enhancer) {    // 初始化参数    let currentReducer = reducer      // 整个reducer    let currentState = preloadedState //当前的state, getState返回的值就是他,    let currentListeners = []         // 当前的订阅,搭配 nextListeners    let nextListeners = currentListeners  //下一次的订阅 ,搭配currentListeners    let isDispatching = false  //是否处于 dispatch action 状态中        // 内部方法    function ensureCanMutateNextListeners() { }  // 确保currentListeners 和 nextListeners 是不同的引用    function getState() { }    // 获得当前的状态,返回的就是currentState    function subscribe(listener) { }  //订阅监听,返回一个函数,执行该函数,取消监听    function dispatch(action) { }    // dispacth action    function replaceReducer(nextReducer) { }  // 替换 reducer    function observable() { }   //不知道哈哈        //初始化state    dispatch({ type: ActionTypes.INIT })       //返回方法    return {        dispatch,        subscribe,        getState,        replaceReducer,        [$$observable]: observable    }}

 

ensureCanMutateNextListeners

这个方法主要用在 subscribe里面,

  • 在每次订阅和取消订阅的时候,会让 nextListeners 和 currentListeners 不是同一个引用,
  • 在每次 dispatch的时候,当 reducer执行完毕,订阅执行前,让 nextListeners 和 currentListeners 是一个引用  
  function ensureCanMutateNextListeners() {    if (nextListeners === currentListeners) {      nextListeners = currentListeners.slice()    }  }

  为什么这么设计,在subscribe方法上有很详细的注解,我的理解是假如订阅在执行过程中,这里说的是订阅执行过程,不是reducer执行过程

       有新加的订阅添加的时候,新的订阅是不会被执行的,因为是一份拷贝

       有新的订阅删除的时候,被删除的还是会执行的。

       简单说,就是新的删除和添加,下次生效。

 
getState
就是返回利用闭包存的currentState
  /**   * Reads the state tree managed by the store.   *   * @returns {any} The current state tree of your application.   */  function getState() {    return currentState  }

 

 subscribe

   添加订阅

  • 每次添加前,如果 nextListeners 和 currentListeners 是一个引用,重新复制一个
  • 并存入 nextListeners 
  • 返回一个函数,执行该函数取消订阅,
  function subscribe(listener) {    if (typeof listener !== 'function') {      throw new Error('Expected listener to be a function.')    }    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) // 从nextListeners里面删除,下次dispatch会生效    }  }

 

dispatch

派发一个action,让reducer更新数据,下面都有注释了,为啥可说的。
  •  如果上一次派发没完毕,接着派发是会出异常的,对于单线程的js来说倒是没啥大问题
  function dispatch(action) {    if (!isPlainObject(action)) { // action 必须是对象      throw new Error(        'Actions must be plain objects. ' +        'Use custom middleware for async actions.'      )    }    if (typeof action.type === 'undefined') {  // 必须有type属性      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  // 标记,正在派发      currentState = currentReducer(currentState, action)    } finally {      isDispatching = false  //标记派发完毕    }         const listeners = currentListeners = nextListeners  // 让nextListeners生效    for (let i = 0; i < listeners.length; i++) {  // 挨个执行订阅      const listener = listeners[i]        listener()    }    return action // 返回action  }

  

replaceReducer
 function replaceReducer(nextReducer) {    if (typeof nextReducer !== 'function') {  // 不是函数,抛出异常      throw new Error('Expected the nextReducer to be a function.')    }    currentReducer = nextReducer  // 替换reducer    dispatch({ type: ActionTypes.INIT }) // 重新初始化  }

  

observable 还没啥研究,暂不说了。
最后的代码为, 
  • 初始化 state
  • 返回相关方法
  dispatch({ type: ActionTypes.INIT })  return {    dispatch,    subscribe,    getState,    replaceReducer,    [$$observable]: observable  }

  这里说一下 dispatch({ type: ActionTypes.INIT }) 是怎么达到初始化state的,

  我们再回头看一下disptach中的一段代码

    try {      isDispatching = true      currentState = currentReducer(currentState, action)    } finally {      isDispatching = false    }

      这里先讲非合成的reducer,带合成的后面说。

   createStore的第一个参数为 reducer,第二个为初始化state的默认值,

  •  如果你传入了第二个参数,currentState就等于你传入的值,而执行一次 dispatch的时候,系统定义的 type 为@@redux/INIT的action,你肯定是没有定义的额,看下面代码,就会直接返回state,   那么执行 currentReducer(currentState, action) 得到的结果还是 currentState
  • 如果你没有传入第二个参数,在reducer的第一个参数指定了默认值,那么reducer处理type为 @@redux/INIT的action的时候,返回的就是reducer第一个参数 state的默认值,然后被赋值给了currentState
  • 如果没有传入第二个参数,同时reducer的state也没指定值,那么,你的dispatch一般都会报错,因为你的state从开始就是undefined
  • 如果recuder函数和createStore都设置了默认了,那么reducer的默认值是不会生效的
let todoReducer = function (state = todoList, action) {    switch (action.type) {        case 'add':            return [...state, action.todo]        case 'delete':            return state.filter(todo => todo.id !== action.id)        default:            return state    }}

  这里相对特别的是 合成recuder,后面再说。

 

 到此为止,你只用redux的createStore方法,就能完成数据控制了,combineReducers,bindActionCreators,applyMiddleware,compose 都只是对redux的增强。

再回头看看我们第一篇提到的代码:(云淡风轻)

  • 初始化的state在recuder赋值,和在createStore赋值是等价的,都赋值的话,createStore的赋值会生效。 (createStore用的是显示赋值, reducer:默认参数) 
/* 简单示例 */let { createStore } = self.Redux//默认statelet todoList = []// reducerlet todoReducer = function (state, action) {    switch (action.type) {        case 'add':            return [...state, action.todo]        case 'delete':            return state.filter(todo => todo.id !== action.id)        default:            return state    }}//创建storelet store = createStore(todoReducer,todoList)//订阅function subscribe1Fn() {    console.log(store.getState())}let sub = store.subscribe(subscribe1Fn)store.dispatch({    type: 'add',    todo: {        id: 1,        content: '学习redux'    }})store.dispatch({    type: 'add',    todo: {        id: 2,        content: '吃饭睡觉'    }})store.dispatch({    type: 'delete',    id: 2})// 取消订阅sub()console.log('取消订阅后:')store.dispatch({    type: 'add',    todo: {        id: 3,        content: '打游戏'    }})

   

版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

热门文章
  • 机房智能化温湿度解决方式之POE供电以太网温湿度传感器

    机房智能化温湿度解决方式之POE供电以太网温湿度传感器
    机房智能化温湿度解决方式之POE供电以太网温湿度传感器 北京盈创力和电子科技有限公司 智能型TCP网口温湿度记录仪 北京IP网络温湿度记录仪厂家,北京盈创力和 北京智能型TCP网口温湿度记录仪IP网络温湿度记录仪是一种新型的基于TCP/IP协议双绞线以太网标准温湿度采集模块,利用它可以实现现场温度值、相对湿度值的采集,同时利用其自身的RJ45通信接口可以方便地和机房监控主机或交换机集线器进行联网。 工作于-40℃~85℃工业级带...
  • Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering

    Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering
    Problem Statement 我们考虑一个具有马尔可夫性质、非线性、非高斯的状态空间模型(State Space Model):对于一个时间序列上的观测结果{yt,t∈N}\\{ y_t , t \\in N \\}{yt​,t∈N},我们认为每个观测结果yty_tyt​的生成依赖于一个无法直接观察的隐变量xt∈{xt,t∈N}x_t \\in \\{x_t , t \\in N \\}xt​∈{xt​,t∈N},即:p(...
  • HTTP状态保持的原理

    HTTP状态保持的原理
    a)在用户登录之后,浏览器返回响应的时候会在响应中添加上cookieb)浏览器接收到cookie之后会自动保存c)当用户再次请求同一服务器中的其他网页的时候,浏览器会自动带上之前保存的cookied)服务接收到请求之后可以请 request 对象中取到cookie 判断当前用户是否登录  Http是无状态的,就是连接时数据互通,关闭后...
  • Hive 系统函数及示例

    Hive 系统函数及示例
    查看所有系统函数 show functions; 函数分类 内置函数【系统函数】 数学函数: floor、round、ceil、cos、log2等 字符串函数: length、reverse、trim、lower、get_json_object、repeat等 收集函数: size 转换函数: cast 日期函数: year、month、datediff、date、date_add等 条件函数: coalesce、case…w...
  • CSRF的原理和防范措施

    CSRF的原理和防范措施
    a)攻击原理:i.用户C访问正常网站A时进行登录,浏览器保存A的cookieii.用户C再访问攻击网站B,网站B上有某个隐藏的链接或者图片标签会自动请求网站A的URL地址,例如表单提交,传指定的参数iii.而攻击网站B在访问网站A的时候,浏览器会自动带上网站A的cookieiv.所以网站A在接收到请求之后可判断当前用户是登录状态,所以...
标签列表