thunk 是一個(gè) Redux 的中間件(Middleware)。
1. 添加和配置thunk到項(xiàng)目:
2. 應(yīng)用thunk
//store & thunk
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 enhancer = composeEnhancers(
applyMiddleware(thunk),
);
const store = createStore(
reducer,
enhancer
);
上述代碼同時(shí)引入了兩個(gè)中間件:redux dev tools 和 redux thunk。
應(yīng)用thunk后,action可以是一個(gè)函數(shù),函數(shù)里面是實(shí)現(xiàn)異步操作(比如數(shù)據(jù)請(qǐng)求)的代碼。當(dāng)這樣的action通過(guò)dispatch()傳給了store時(shí),store識(shí)別到action是一個(gè)函數(shù),然后自動(dòng)執(zhí)行該函數(shù);
需要注意的是,action中往往還需要在異步請(qǐng)求數(shù)據(jù)之后修改store中的數(shù)據(jù)(axios.get().then()),這就又需要調(diào)用store.dispatch()方法。好在action返回的函數(shù)中可以傳入dispatch作為參數(shù),因此可以直接在異步請(qǐng)求代碼之后修改數(shù)據(jù):
//thunk,action是一個(gè)函數(shù)
export const getTodoList = () => {
return (dispatch) => { //返回一個(gè)發(fā)送異步請(qǐng)求的函數(shù)
axios.get('./list.json').then((res)=>{
const data = res.data;
const action = initListAction(data);
dispatch(action);
})
}
}
有了thunk,我們實(shí)現(xiàn)了在actionCreators.js中編寫異步請(qǐng)求,不用把這些代碼堆砌在組件中,避免組件代碼過(guò)于臃腫。