人人能读懂redux原理剖析

一、Redux是什么?

众所周知,Redux最早运用于React框架中,是一个全局状态管理器。Redux解决了在开发过程中数据无限层层传递而引发的一系列问题,因此我们有必要来了解一下Redux到底是如何实现的?

二、Redux的核心思想?

在这里插入图片描述

Redux主要分为几个部分:dispatchreducerstate
我们着重看下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 < listeners
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值