Asynchronous Redux middleware Redux order

Time:2021-1-27

redux-order

Redux order is a middleware to deal with Redux, which simplifies the asynchronous flow control processing of redux.

install

npm install redux-order

Introducing Redux order

import {createStore, applyMiddleware, compose} from 'redux';
import reduxOrder from 'redux-order';
import reducers from './reduces';

const enhancer = compose(
  //Introduction of Middleware
  applyMiddleware(reduxOrder())
);

const store = createStore(
  reducers,
  enhancer
);

export default store;

Asynchronous processing in reduce

// action
const LOGIN = 'auth/LOGIN';
const LOGIN_SUCCESS = 'auth/LOGIN_SUCCESS';
const LOGIN_FAIL = 'auth/LOGIN_FAIL';

const initialState = {};
// reducer
export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case LOGIN:
      console.log(action);
      return {
        ...state,
        requesting: true,
        requested: false,
    };
    case LOGIN_SUCCESS:
      console.log(action);
      return {
        ...state,
        requesting: false,
        requested: true,
        auth: action.res
    };
    case LOGIN_FAIL:
      console.log(action);
      return {
        ...state,
        requesting: false,
        requested: true,
        loginError: action.err
    };
    default:
      return state;
  }
}
//Trigger action
export function login(user, pass) {
  return {
    types: [LOGIN, LOGIN_SUCCESS, LOGIN_FAIL],
    promise: axios.post('/api/login', {user, pass}),
    data: 'message',
    list: [1, 2, 3, 4]
  };
}

Asynchronous action

  • In the example above, we createdasynchronousRedux request for. This is defined in the exampleLOGINLOGIN_SUCCESSLOGIN_FAILThe three actions represent request sending, request success and request failure in turn. When issuing an asynchronouspromiseAfter the request, theLOGINIf the request is successful, enterLOGIN_SUCCESSOtherwise, they will enterLOGIN_FAIL
  • Asynchronous actions need to be definedtypes, types is an array, and at least two actions (request and result) are required,promiseThe parameter is an asynchronous request, which must be a promise object.
  • The result of the request is obtained in the action object in the reducer. If it is successful, the return result isaction.reqWhat failed wasaction.err
  • When you issue an action, you can also carry a payload. You can customize the parameters you need to carry, and you can access the parameters carried by action in reducer.

Synchronous action

export function logout() {
  return {
    type: LOGOUT
  };
}

The above is to trigger a synchronous action,typeParameters define the actions to be triggered, and can also carry payload. be careful ⚠️ The asynchronous action parameter istypes, while synchronous istype

GitHubaddress