一、redux-thunk介紹
redux-thunk用於處理異步action,同類型的有redux-saga
二、學習網址
https://github.com/reduxjs/redux-thunk github
三、安裝與引入
npm install --save react-redux
安裝
import thunk from 'redux-thunk'
引入
三、如何使用redux-thunk
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
// 創建store的時候,第二個參數是中間件,redux-thunk提供了一個thunk中間件,用於處理異步的action
export default createStore(
rootReducer,
applyMiddleware(thunk)
);
//異步的action, 由於使用了redux-thunk的thunk中間件,
//所以,在這個action裏不用像同步action那樣,必須返回一個對象,在這裏返回一個方法
//這個方法有一個dispatch的參數,這個dispatch就是store裏的dispatch.
export const addAsync = (num = 1) => {
return (dispatch) => {
// 當這個方法剛進來的時候,就馬上告訴reducer,我要開始獲取數據了,
// reducer接收到這個動作,就會執行相應的操作(把isLoading改爲true,看reducer裏的代碼)
dispatch({
type: START_GET_DATA
});
// 用setTimeout來模擬獲取數據
setTimeout(() => {
// 獲取數據完成之後,需要dispatch兩個action.
// 一個是把獲取到的數據,傳到一個動作裏(ADD)
dispatch({
type: ADD,
num
});
// 這個是用來告訴reducer,我獲取數據成功了。reducer接收到這個動作,
// 就會執行相應的操作(把isLoading改爲false,看reducer裏的代碼)
dispatch({
type: GET_DATA_SUCCESS
});
}, 2000)
}
}