用实例来理解redux

来源:互联网 发布:驾照模拟考试c1软件 编辑:程序博客网 时间:2024/06/09 16:01

     公司有物流(actionType)、电商(actionType)和销售(actionType)三个独立部门,各有自己的财务人员,根据自己的业务逻辑(reducer)去处理财务信息。然后公司有个财务系统(state),统一管理了各个部门的财务信息。

     某天销售部门销售出100w的商品(action),销售拿着销售发票(dispatch)到部门的财务人员报账,财务根据自己的业务逻辑(reducer)处理完后,把信息报上了财务系统(state)。

     公司老板想要时刻关注着公司财务状况,于是在系统的提醒设置(subscribe)中设置了提醒功能,在有访问到财务系统的行为时,会触给老板发提醒(listener)。

原理

     在触发一个action后,把处理后的结果,通过dispatch发送到reducer中,reducer会根据传过来的actionType去更新相应的state数据。接着,会遍历所有的订阅事件,并调用订阅的事件。


API
function createStore(reducer, preloadedState, enhancer)

createStore会创建redux环境,并根据传入的preloadedState做为state的初始值。
在单页面应用中,createStore只能被调用一次,并使用此方法返回来的api去操作state。

createStore返回来的api:

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

dispatch: 把想要更新的数据通过dispatch传递到reducer中,dispatch的参数必须为一个普通js对象,并且包含一个type的属性值。

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      // 把action传递到reducer中,并更新state      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  }

subscribe: 注册监听事件,在有数据通过dispatch传到redux环境后,会触发所有的监听事件运行。

// 注册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)    }  }
原创粉丝点击