redux-order是處理redux的中間件,簡化redux的異步流控制處理。
npm install redux-order
引入redux-orderjavascript
import {createStore, applyMiddleware, compose} from 'redux'; import reduxOrder from 'redux-order'; import reducers from './reduces'; const enhancer = compose( //引入中間件 applyMiddleware(reduxOrder()) ); const store = createStore( reducers, enhancer ); export default store;
reduces中處理異步java
// 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; } } // 觸發 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] }; }
異步
的redux請求。例子中定義了LOGIN
、LOGIN_SUCCESS
、LOGIN_FAIL
三個action,依次表明請求發出、請求成功、請求失敗。在發出一個異步promise
請求後,首先觸發了LOGIN
,假如請求成功則進入LOGIN_SUCCESS
,不然就進入LOGIN_FAIL
。types
,types爲數組而且至少須要兩個action(發出請求和結果),promise
參數爲異步請求,異步請求必須爲promise對象。action.req
,失敗的則是action.err
。export function logout() { return { type: LOGOUT }; }
上面爲觸發一個同步的action,type
參數定義要觸發的動做,一樣也能夠攜帶payload。注意⚠️異步的action參數爲types
,而同步的爲type
。ios