Redux Middleware
Middleware: Similar to plug-ins, functionality can be enhanced without affecting the original functionality and without changing the original code. In Redux, the middleware is primarily used to enhance the Dispatch function.
The basic principle of implementing Redux middleware is to change the Dispatch function in the repository.
Simple scenario
For example, you want to print the data before and after the store changes
import { createStore, bindActionCreators } from ".. /redux"; import reducer from "./reducer" const store = createStore(reducer); const oldDispatch = store.dispatch; // Keep the original dispatch function store.dispatch = function (action) {// Change the store's dispatch console.log(" middleware 1") console.log(" old data "), store.getState()); console.log("action", action); oldDispatch(action); Console. log(" new data ", store.getState()); console.log("") }Copy the code
Is that how you code?? Certainly not. The core principle is to save the previous dispatch function for the next middleware.
Real implementation of handwriting middleware
Redux middleware writing:
- The middleware itself is a function that takes a store parameter, which represents the repository that was created. The repository is not a complete repository object, but contains only getState and Dispatch. This function runs after the repository is created.
- Since the set middleware functions need to be run automatically after the repository is created, you need to tell the repository what middleware is available when the repository is created
- You need to call the applyMiddleware function and return the result as the second or third argument to the createStore.
- The middleware function must return a dispatch create function
// The middleware itself is a function, Export const journalMiddle = function (store) {// The middleware function must return a dispatch. The create function next is the new dispatch passed before and after the middleware component Return function (action) {console.log("journalMiddle Pre Store state", store.getState()); next(action); console.log("journalMiddle new store state", store.getState()); }; }; }; //index.js apply import {createStore, bindActionCreators, applyMiddleware} from "redux"; import redercer from "./reducer/index.js"; import * as actionAll from "./action/number-action"; import { journalMiddle } from "./writeMiddleware/index"; const store = createStore(redercer, applyMiddleware(journalMiddle));Copy the code
The print result is as follows
This satisfies the need to print logs