上兩篇文章敘述的都是同步操作,每當 dispatch action 時,state 會被立即更新。但是實際應用中,我們有很多操作執行后,過一段時間,才會得到結果。那么怎么處理這種情況呢?
先熟悉一個概念
中間件
本質就是一個通用函數,可以在程序的任何執行處介入,從而將處理方法擴展到現有系統上。
在store.dispatch(action) 執行時候,打印日志,這就是一個簡單的中間件
let next = store.dispatch;
store.dispatch = action => {
next(action);
console.log('state after dispatch', getState())
}
引入中間件 redux-thunk
redux-thunk中間件,允許action creator返回一個函數,這個函數會接收dispath和getState?為參數。
看下面三種不同的action
const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
普通的,返回一個對象
function increment() {
return {
type: INCREMENT_COUNTER
};
}
異步的,返回一個函數
function incrementAsync() {
return dispatch => {
setTimeout(() => {
// Yay! Can invoke sync or async actions with `dispatch`
dispatch(increment());
}, 1000);
};
}
帶條件的,返回一個函數
function incrementIfOdd() {
return (dispatch, getState) => {
const { counter } = getState();
if (counter % 2 === 0) {
return;
}
dispatch(increment());
};
}
使用中間件 redux-thunk
需求:
進入頁面之后,點擊某個按鈕,獲取用戶投資總額。。。
分析:
異步請求有3個關鍵action
開始請求--一般用于呈現加載進度條
請求成功--關閉進度條,加載數據
請求失敗--關閉進度條,展示錯誤信息
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk'; //導入thunk
import rootReducer from './reducers/index';
// Note: this API requires redux@>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(thunk)//激活thunk中間件
);
//一個異步請求
function fetchAmount() {
return fetch('https://www.renrendai.com/getAmount?userId=123')
}
//通知 reducer 請求開始的 action
requestPost(){
return{
type: REQUEST_POSTS,
isFetch:true //進度條相關
}
}
//通知 reducer 請求成功的 action
receviePostOnSuccess( data){
return{
type: RECEIVE_POSTS,
isFetch:false,
amount: data.amount
}
}
//通知 reducer 請求失敗的 action。
receviePostOnError( message){
return{
type: RECEIVE_POSTS,
isFetch:false,
errorMsg:message
}
}
//異步請求action 【將上面3個基礎的action整合】
function getAmount(){
retrun (dispath)=>{
// 首次 dispatch:更新應用的 state 來通知API 請求發起了
dispatch(requestPosts())
//異步請求后端接口
return fetchAmount().then(
data=>dispath(receviePostOnSuccess(data)),
error=> dispatch(receviePostOnError('error))
)
}
}
也很容易理解吧~~~
本文檔是將最基礎的使用方法提煉呈現,真正的react-redux博大精深,如果想繼續深究,就趕緊找一個簡單的項目開始練手吧。
參考文檔: