上兩篇文章敘述的都是同步操作,每當 dispatch action 時猖任,state 會被立即更新你稚。但是實際應用中,我們有很多操作執(zhí)行后朱躺,過一段時間刁赖,才會得到結果。那么怎么處理這種情況呢长搀?
先熟悉一個概念
中間件
本質就是一個通用函數(shù)宇弛,可以在程序的任何執(zhí)行處介入,從而將處理方法擴展到現(xiàn)有系統(tǒng)上源请。
在store.dispatch(action) 執(zhí)行時候枪芒,打印日志彻况,這就是一個簡單的中間件
let next = store.dispatch;
store.dispatch = action => {
next(action);
console.log('state after dispatch', getState())
}
引入中間件 redux-thunk
redux-thunk中間件,允許action creator返回一個函數(shù),這個函數(shù)會接收dispath和getState舅踪?為參數(shù)纽甘。
看下面三種不同的action
const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
普通的,返回一個對象
function increment() {
return {
type: INCREMENT_COUNTER
};
}
異步的,返回一個函數(shù)
function incrementAsync() {
return dispatch => {
setTimeout(() => {
// Yay! Can invoke sync or async actions with `dispatch`
dispatch(increment());
}, 1000);
};
}
帶條件的抽碌,返回一個函數(shù)
function incrementIfOdd() {
return (dispatch, getState) => {
const { counter } = getState();
if (counter % 2 === 0) {
return;
}
dispatch(increment());
};
}
使用中間件 redux-thunk
需求:
進入頁面之后贷腕,點擊某個按鈕,獲取用戶投資總額咬展。泽裳。。
分析:
異步請求有3個關鍵action
- 開始請求--一般用于呈現(xiàn)加載進度條
- 請求成功--關閉進度條破婆,加載數(shù)據(jù)
- 請求失敗--關閉進度條涮总,展示錯誤信息
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 請求發(fā)起了
dispatch(requestPosts())
//異步請求后端接口
return fetchAmount().then(
data=>dispath(receviePostOnSuccess(data)),
error=> dispatch(receviePostOnError('error))
)
}
}
也很容易理解吧~~~
本文檔是將最基礎的使用方法提煉呈現(xiàn)祷舀,真正的react-redux博大精深瀑梗,如果想繼續(xù)深究,就趕緊找一個簡單的項目開始練手吧裳扯。
參考文檔: