redux 中間件

redux中間件的執行順序

action ---> dispatcher ---> middleware 1 ---> middleware 2 ---> reducersjavascript

redux中間件函數必須遵循一個嚴格的函數結構

var anyMiddleware = function ({ dispatch, getState }) {
    return function(next) {
        return function (action) {
            // your middleware-specific code goes here
        }
    }
}
  1. 函數的第一級獲得2個參數 dispatch 和 getState
    調用 getState() 獲得store中的整個statejava

  2. 函數的第二級提供 next 參數
    執行next() 執行下一個中間件或者到redux ,這樣就能夠按順序執行中間件redux

  3. 函數的第三級提供執行的 ancion 參數
    根據action 能夠執行相應的操做promise

經常使用的中間件

logMiddleware

打印日誌異步

function logMiddleware ({ dispatch, getState }) {
    return function(next) {
        return function (action) {
            console.log('logMiddleware action received:', action)
            return next(action)
        }
    }
}

discardMiddleware

一箇中間件丟棄全部發送的操做
(這個不是很是有用的,但有一點邏輯,它能夠選擇性地放棄一些action,而經過其餘action)ide

function discardMiddleware ({ dispatch, getState }) {
    return function(next) {
        return function (action) {
            console.log('discardMiddleware action received:', action)
        }
    }
}

redux-thunk

異步中間件用於action異步操做函數

var thunkMiddleware = function ({ dispatch, getState }) {
    // console.log('Enter thunkMiddleware');
    return function(next) {
        // console.log('Function "next" provided:', next);
        return function (action) {
            // console.log('Handling action:', action);
            return typeof action === 'function' ?
                action(dispatch, getState) :
                next(action)
        }
    }
}

redux-promise

異步中間件用於action異步操做fetch

var thunkMiddleware = function ({ dispatch, getState }) {
    // console.log('Enter thunkMiddleware');
    return function(next) {
        // console.log('Function "next" provided:', next);
        return function (action) {
           if (!isFSA(action)) {
              return isPromise(action) ? action.then(dispatch) : next(action);
              }
              
              
           return isPromise(action.payload)
              ? action.payload.then(
                  result => dispatch({ ...action, payload: result }),
                  error => {
                    dispatch({ ...action, payload: error, error: true });
                    return Promise.reject(error);
                  }
                )
              : next(action);
        }
    }
}

調用方式url

function action(){
    return {
        type:'ADD_USER',
        payload:fetch('url')
    }
}
相關文章
相關標籤/搜索