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来统一管理数据。
Atas ialah kandungan terperinci 如何理解 redux. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!
Apakah teknologi teras yang diperlukan untuk pembangunan Java?
Penggunaan kelas kalendar dalam java
IIS penyelesaian ralat tidak dijangka 0x8ffe2740
sublime menjalankan kod js
Cara menghantar lokasi anda kepada orang lain
Perbezaan antara vue3.0 dan 2.0
Perkara yang perlu dilakukan jika folder dokumen muncul apabila komputer dihidupkan
Matikan kemas kini automatik win10