Redux Principle
A company has three businesses: logistics (actionType), e-commerce (actionType), and advertising (actionType) , the funds earned from the three businesses are uniformly recorded in the company's financial system (state). One day, the e-commerce business sold 1 million worth of goods (actions) on the company's e-commerce platform. The funds earned were sent to the business's financial department in the form of invoices (dispatch). The financial department calculated the earnings through its own business blocks. The profit obtained (reducer) is then updated to the financial system (state).
Core principle: Through an event action, the results are sent to the reducer through dispatch. In the reducer, different business processes are performed on the data according to different actionTypes, and then the final results are updated into the state tree.
Since several of my bosses keep a close eye on the company's funds and must always pay attention to changes in funds, they set up an event (subscribe) to send a text message to notify them (listener) when there is a change in funds.
Principle: Redux has a built-in listeners array that allows external subscriptions to state data change events. When the data in the state tree changes, all listening events will be notified.
API explanation
function createStore(reducer, preloadedState, enhancer)
In the createStore method, the entire redux environment is initialized. preloadedState serves as the initial value of the state tree. This method returns the open interface of redux, and the state of redux can only be operated through the returned api.
CreateStore returns the returned API:
##
return { dispatch, subscribe, getState, replaceReducer, [$$observable]: observable }
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) } }
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 }
The above is the detailed content of How to understand redux. For more information, please follow other related articles on the PHP Chinese website!