use

React asynchronous operations, such as a normal background system, pop-up window close, need to refresh the list and other basic operations. Or the user enters the system, logs in first, after logging in successfully, gets the login information and then makes the relevant request.

The principle of

Since store’s method is dispatch, its argument is an object like {type: ‘add’, payload}, redux-thunk (), payloads (), payloads (), payloads (), payloads (), payloads ()) The core code is really just two lines of code that determines each action that passes through it: if it is function, call this function (with dispatch and getState and extraArgument as arguments).

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

Why we need it

In fact, it is possible to do asynchronous operations without middleware, that is, to write directly in the relevant parts of the business layer code, such as the above example, after the request is successful, then send another action, but with middleware we can put some callbacks in the public function, easy to call

usage

First, let’s look at the use of this library. Redux-thunk redux-thunk is used as middleware for redux and is used in the same way as normal middleware. The code to register middleware is as follows:

import thunkMiddleware from 'redux-thunk'
const store = createStore(reducer, applyMiddleware(thunkMiddleware))
Copy the code

After registration, it can be used as follows:

Const login = (userName) => (dispatch) => {dispatch({type: 'loginStart' }) request.post('/api/login', { data: userName }, () => { dispatch({ type: 'loginSuccess', payload: userName }) }) } store.dispatch(login('Lucy'))Copy the code

As you can see, the main function of redux-Thunk is to dispatch a function, not just a normal Object. As we’ll see later, this change gives us tremendous flexibility.

reference

zhuanlan.zhihu.com/p/85403048