While using createStore in Redux today, I took a look at the GIthub API and the third parameter, enhancer, caught my eye. All I know is that the third parameter, applyMiddleware, provides an asynchronous function that enhances dispatch. As for the implementation process, it’s really not well studied.
Structural analysis of ENHancer
Redux createStore createStore createStore createStore createStore createStore createStore createStore
In the createStore function, there is only so much code for enhancer, which basically means to determine whether the enhancer exists, whether it is a function, and that the enhancer request must return a function.
So I have written the rough structure of enhancer as follows:
The purpose of enhancer
After analyzing the structure of enhancer, what is in it and what is its purpose? Here we mainly refer to the return before it.
That is, when we pass in the third argument, the code execution ends here, but the createStore is asking for a store object, so we know that enhancer is still returning a store object, but the store object is an enhanced store. So, the new enhancer structure looks like this:
This doesn’t work, because it returns the same store as the store that didn’t pass enhancer. Where is the enhancer? So I immediately thought of dispatch, which has two forms when it is executed. The first form parameter action is an object, and the second form parameter action is a function, so I changed the code:
So the purpose of enhancer is to add dispatch functionality. For example, if we encounter asynchronous code, we can pass in enhancer.
We passed the written enhancer into createStore and a function with asynchronous code into Dispatch. Thus enhancer enhances dispatch. Remember that enhancer is a manual implementation, not an official one. The official one only tells us the internal structure.