The core concept of Redux is actually very simple: store all the states that need to be modified in the store, initiate an action to describe what happened, and use reducers to describe how the action changes the State tree. Reducer is needed when creating a store. It is the Store. dispatch API that can change the data in the store.
1. The concept
After dispatching an action and before arriving at the Reducer, additional actions are needed. You can use Redux Middleware for logging, creating crash reports, calling asynchronous interfaces, routing, and more.
In other words, middleware is all enhancements to store.dispatch()
2. Usage of middleware
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
reducers,
applyMiddleware(thunk)
);
Copy the code
Adding thunk middleware directly to the applyMiddleware method and passing in the createStore method completes the enhancements to store.dispatch(). That is, some asynchronous operations can be done in the Reducer.
3.applyMiddleware()
ApplyMiddleware is a native method of Redux that takes all the middleware in an array and executes it in turn. More middleware can be passed as parameters in turn
const store = createStore(
reducers,
applyMiddleware(thunk, logger)
);
Copy the code
If you want to understand its evolution process can go to the story of the official document: https://redux.js.org/advanced/middleware
4.redux-thunk
Node_modules /redux-thunk/ SRC /index.js
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
Copy the code
CreateThunkMiddleware export default is createThunkMiddleware(). CreateThunkMiddleware returns a Curryized function. Let’s translate the ES5 code to make it easier to see,
function createThunkMiddleware(extraArgument) {
return function({ dispatch, getState }) {
return function(next){
return function(action){
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
returnnext(action); }; }}}Copy the code
The most important idea behind Redux-Thunk is action Creator, which accepts a return function. If this Action Creator returns a function, execute it; if not, follow the original next(Action).
Because this Action Creator can return a function, you can perform some asynchronous operations in this function. Such as:
export function addCount() {
return {type: ADD_COUNT}
}
export function addCountAsync() {
return dispatch => {
setTimeout( () => {
dispatch(addCount())
},2000)
}
}
Copy the code
The addCountAsync function returns a function that passes dispatch as its first argument and does the asynchronous operation within the function.
Reference: http://www.redux.org.cn/docs/advanced/Middleware.html