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来统一管理数据。
以上就是如何理解 redux的详细内容。
