action在到達store之前會經歷一個中間件層,利用redux中間件機制,可以在action響應之前執行其他額外的業務邏輯。中間件指的是是action 與store的中間,是redux的中間件。
1.先安裝
npm install redux-thunk --save
2.在index.js里創建store時配置redux-thunk。
要想使用中間件,需要在創建store的index.js文件里,引入applyMiddleware,照着官方的文檔一步一步配置,使得store既使用了redux-thunk這個中間件,又使用了redux-doctools這個開發者工具。這樣在action來的時候,會經過這些中間件,從而做額外的操作。
index.js:
import { createStore, applyMiddleware ,compose} from 'redux'; import reducer from './reducer' import thunk from 'redux-thunk' const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose; const store=createStore(reducer,composeEnhancers(applyMiddleware(thunk))); export default store;
3.在actionCreators.js的action 里寫異步的代碼
因為有了thunk這個中間件,所以action可以是一個函數,這個函數有2個參數是dispatch、getState。store發現action 是一個函數,會自動執行這個函數。
actionCreators.js
import * as actionTypes from './actionTypes'; import{ fromJS } from 'immutable' import axios from 'axios'; export const searchFocusAction=()=>({ type:actionTypes.SEARCH_FOCUS }); export const searchBlurAction=()=>({ type:actionTypes.SEARCH_BLUR }); export const listInitAction=(data)=>({ type:actionTypes.LIST_INIT, data:fromJS(data) }); export const getList=()=>{ //action可以是一個函數,有dispatch參數 return (dispatch)=>{ axios.get('/api/headerList.json').then((res)=>{ const data=res.data; dispatch(listInitAction(data.data)) }).catch(()=>{ console.log('error'); }); } };