Redux Synchronous operation

The basic use of Redux is as follows:

dispatch
Action
reducer
state
synchronous
Action
reducer
state
Calculate state asynchronously

Redux Asynchronous operation

In Redux, the Action object is a simple JS object that expresses the user’s intention to modify state. Reducer is also a pure JS function that only calculates state according to the Action object and does not perform API requests or route jumps. So, we can only do something when we send the Action, which is to modify the dispatch method so that it can operate asynchronously.

Redux-thunk is a piece of middleware used by Redux that wraps the store object’s native dispatch method and returns a new dispatch method. We pass this new dispatch method a function, dispatch(func), in which we perform the asynchronous operation, and then we perform the native dispatch(action) operation in the callback method of the asynchronous operation, modifying the state.

    import { createStore, applyMiddleware } from 'redux'
    import thunk from 'redux-thunk'// Return an Action object const Action = text => {value: Const post = () => Dispatch => {// Asynchronous operationsetTimeout(() =>{
            dispatch(Action('123'))
        }, 2000)
    }
    
    // reducer
    const reducer = (state, action) {
        ...
        returnstate; Const Store = createStore(Reducer, applyMiddleware(... Middle)) // Synchronous operation store.dispatch(Action('123')); // Asynchronous operation store.dispatch(post())Copy the code

Redux Asynchronous parsing

redux-thunk:

// Redux Use redux-Thunk via applyMiddleware The createThunkMiddleware method is first executed // passing in the redux native dispatch/getState method // or passing in the dispatch/getState after the last middleware wrapperfunction createThunkMiddleware(extraArgument) {
     return({dispatch, getState}) => Next => Action => {// If action is a function, that is, a thunk function, execute thunk function directlyif (typeof action === 'function') {
         returnaction(dispatch, getState, extraArgument); } // If acton is not a function, call the native dispatch method to dispatch the Action and change the statereturn next(action);
     };
   }
   
   const thunk = createThunkMiddleware();
   thunk.withExtraArgument = createThunkMiddleware;
   
   export default thunk
Copy the code

applyMiddleware:

    export default functionapplyMiddleware(... Middlewares) {// Return enhancer, createStore => createStorereturn=> (reducer, preloadedState, enhancer) => {// execute the native redux createStore method, Create a store object const Store = createStore(Reducer, preloadedState, enhancer) // native Dispatch methodlet dispatch = store.dispatch
        let{chain = [] const middlewareAPI = {store.getState; (action) => dispatch(action) } // [chainA, chainB, chainC, chainD], Next => Action chain = middlewares. Map (Middleware => Middleware (middlewareAPI)) ChainA (chainB(chainC(chainD(store.dispatch)))) // dispatch is the compose of dispatch method dispatch = compose(... Chain)(store.dispatch) // Returns a new Store object and the dispatch method is rewrappedreturn {
          ...store,
          dispatch
        }
      }
    }
Copy the code

Through the applyMiddleware method and Thunk middleware, the store object’s native Dispatch method is packaged as follows:

// Dispatch methodfunction (action) {
        if (typeof action === 'function') {
            return action(dispatch, getState, extraArgument);
        }
        return dispatch(action);
    }
    
Copy the code

Store.dispatch (Action(‘123’)), we call the wrapped dispatch method, because Action(‘123’) returns an object, not a function, So the new dispatch method will call the store’s native Dispatch method directly, and then dispatch the Action, triggering the change in state.

Store.dispatch (post()), we call the same wrapped dispatch method, post() returns the function thunk, so thunk is automatically executed. In the thunk function, we can perform an asynchronous operation, then call the store’s native Dispatch method in the callback method of the asynchronous operation, dispatch an Action, and trigger a change in state.

To summarize, the asynchronous operation process of Redux is as follows: