## 使用`axios`和`middleware`優化`API`請求
先安裝下[axios](https://github.com/mzabriskie/axios)
`npm install --save axios`
既然用到了`redux`,配合中間件優化`API`請求,`actions`創建函數時這樣的(比我們現在寫的`fetch`簡單多了):
~~~
export function getUserInfo() {
return (
types: [GET_USER_INFO_REQUEST, GET_USER_INFO_SUCCESS, GET_USER_INFO_FAIL],
promise: client => client.get('http://10.10.100.217:10088/api/userInfo.json'),
afterSuccess: (dispatch, getState, response) => {
/*請求成功后執行的函數*/
},
otherDate: otherData
)
}
~~~
[中間件的教程](http://cn.redux.js.org/docs/advanced/Middleware.html)
然后再`dispatch(getUserInfo())`后,通過`redux`中間件來處理請求邏輯:
接下來分析一下中間件所需要的邏輯
1. 請求之前需要執行`dispatch` 的 `REQUEST`請求。
2. 成功后就需要執行`dispatch` 的 `SUCCESS`請求。(如果定義了`afterSuccess()`函數就調用它。)
3. 如果失敗了就需要執行`dispatch` 的 `FAIL`請求。
Show Me The Code:
~~~
cd src/redux
mkdir middleware
cd middleware
touch promiseMiddleware.js
~~~
`src/redux/middleware/promiseMiddleware.js`
~~~
import axios from 'axios'
export default store => next => action => {
const {dispatch, getState} = store
/* 如果dispatch來的是一個function,此處不做處理,直接進入下一級 */
if (typeof action === 'function') {
action(dispatch, getState)
return
}
/* 解析action */
const {
promise,
types,
afterSuccess,
...rest
} = action
/* 沒有promise,證明不是想要發送ajax請求的,就直接進入下一步啦! */
if (!action.promise) {
return next(action)
}
/* 解析types */
const
}
~~~