设为首页 加入收藏

TOP

对redux的理解
2017-10-10 12:33:27 】 浏览:4420
Tags:redux 理解

   redux原理

  某公司有物流(actionType)、电商(actionType)、广告(actionType)3块业务,在公司财务系统(state)统一记录着三块业务分别赚取到的资金。某天,电商业务在公司电商平台销售了价值100w的商品(action),赚取到的资金通过发票(dispatch)的形式送到业务的财务部门,财务部门通过自己业务块,计算赚取到的利润(reducer),再更新到财务系统(state)。

  核心原理: 通过某个事件action把结果通过dispatch发送到reducer,在reducer中,根据不同的actionType对数据做不同的业务处理,然后把最后的结果更新到state树中。

 

  由于的几位老板对公司的资金盯着很紧,要时刻关注资金的变化,于是,就设置了当资金有变动事件(subscribe),就发短信告诉他(listener)。

  原理:redux通过内置了一个listeners数组,允许外部订阅state数据变动事件,当state树种的数据发生变化,就会通知所有的监听事件。

 

  API 讲解

function createStore(reducer, preloadedState, enhancer)

  createStore方法中,初始化了整个redux环境。preloadedState作为state树的初始值。此方法返回了redux开放的接口,操作redux的state,只能通过返回来的api去操作。

  createStore返回返回来的api:

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

  store.getState: 返回当前redux维护的state对象;

  store.subscribe: 可以通过此接口注册订阅事件,即当redux的state被访问时(不管有没有修改到state的数据),redux就会遍历所有已注册的事件。

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)
    }
  }

  store.dispatch: 在事件action运行后,通过dispatch把结果推送到reducer中。action的结果必须为普通的js对象,并且必须包含一个type属性,在reducer中可以根据type去对数据做不同的业务处理,然后更新到相应的state。

  在reducer之后,无论数据有没有发生变化,都会遍历所有的监听事件。

function dispatch(action) {
    if (!isPlainObject(action)) {
      throw new Error(
        'Actions must be plain objects. ' +
        'Use custom middleware for async actions.'
      )
    }

    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
      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
  }

  整个单页面应用仅需调用1次createStore方法,然后确保初始化后的对象全局可用,这样才能达到通过redux来统一管理数据。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇数据存储 下一篇onblur & onchange

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目