Redux thunk

thunk 是一個(gè) Redux 的中間件(Middleware)。

1. 添加和配置thunk到項(xiàng)目

https://github.com/reduxjs/redux-thunk

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ò)于臃腫。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容