用实例来理解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) } }
阅读全文
0 0
- 用实例来理解redux
- 理解 redux
- redux 理解
- 理解Redux
- 理解redux
- React学习笔记--通过Redux 的三个基本原则来理解Redux
- 用实例来理解IComparable和IComparer
- C#----用实例来理解IComparable和IComparer
- react-redux使用实例
- Redux实例学习
- 深入理解React-Redux
- 深入理解React、Redux
- redux初步理解
- redux middleware 的理解
- react-redux的理解
- 深入理解React、Redux
- Redux中间件源码理解
- 深入理解react-redux
- java和javascript正则表达对比
- linux c动态链接库的使用
- poj2195 Going Home(费用流|KM)
- GYM 101243 F.Vitamins【思维+并查集】
- es6第三版笔记
- 用实例来理解redux
- Echarts3.0入门基础与实战(学习笔记)
- poj 1149 PIGS 最大流 太神奇的建图方式!!!
- SANet:Structure-Aware Network for Visual Tracking 阅读笔记
- Linux网络编程--服务端判断客户端断开的经验方法
- Redhat enterprise 7安装oracle12
- STM32F103x8B PB3、PB4、PA14、PA15引脚作为普通IO口使用
- python小程序:以后台服务方式 定时 监视redis队列 (anaconda3.5.2)
- 用消息系统实现分布式事务