理解 redux-thunk 源碼

2020-6-5    seo達人

前言

前面幾篇我們就 Redux 展開了幾篇文章,這次我們來實現(xiàn) react-thunk,就不是叫實現(xiàn) redux-thunk 了,直接上源碼,因為源碼就11行。如果對 Redux 中間件還不理解的,可以看我寫的 Redux 文章。


實現(xiàn)一個迷你Redux(基礎(chǔ)版)

實現(xiàn)一個Redux(完善版)

淺談React的Context API

帶你實現(xiàn) react-redux

為什么要用 redux-thunk

在使用 Redux 過程,通過 dispatch 方法派發(fā)一個 action 對象。當(dāng)我們使用 redux-thunk 后,可以 dispatch 一個 function。redux-thunk會自動調(diào)用這個 function,并且傳遞 dispatch, getState 方法作為參數(shù)。這樣一來,我們就能在這個 function 里面處理異步邏輯,處理復(fù)雜邏輯,這是原來 Redux 做不到的,因為原來就只能 dispatch 一個簡單對象。


用法

redux-thunk 作為 redux 的中間件,主要用來處理異步請求,比如:


export function fetchData() {

 return (dispatch, getState) => {

   // to do ...

   axios.get('https://jsonplaceholder.typicode.com/todos/1').then(res => {

     console.log(res)

   })

 }

}

redux-thunk 源碼

redux-thunk 的源碼比較簡潔,實際就11行。前幾篇我們說到 redux 的中間件形式,

本質(zhì)上是對 store.dispatch 方法進行了增強改造,基本是類似這種形式:


const middleware = (store) => next => action => {}

在這里就不詳細解釋了,可以看 實現(xiàn)一個Redux(完善版)


先給個縮水版的實現(xiàn):


const thunk = ({ getState, dispatch }) => next => action => {

   if (typeof action === 'function') {

       return action(dispatch, getState)

   }

   return next(action)

}

export default thunk

原理:即當(dāng) action 為 function 的時候,就調(diào)用這個 function (傳入 dispatch, getState)并返回;如果不是,就直接傳給下一個中間件。

完整源碼如下:


function createThunkMiddleware(extraArgument) {

 return ({ dispatch, getState }) => next => action => {

   // 如果action是一個function,就返回action(dispatch, getState, extraArgument),否則返回next(action)。

   if (typeof action === 'function') {

     return action(dispatch, getState, extraArgument)

   }

   // next為之前傳入的store.dispatch,即改寫前的dispatch

   return next(action)

 }

}


const thunk = createThunkMiddleware()

// 給thunk設(shè)置一個變量withExtraArgument,并且將createThunkMiddleware整個函數(shù)賦給它

thunk.withExtraArgument = createThunkMiddleware


export default thunk

我們發(fā)現(xiàn)其實還多了 extraArgument 傳入,這個是自定義參數(shù),如下用法:


const api = "https://jsonplaceholder.typicode.com/todos/1";

const whatever = 10;


const store = createStore(

 reducer,

 applyMiddleware(thunk.withExtraArgument({ api, whatever })),

);


// later

function fetchData() {

 return (dispatch, getState, { api, whatever }) => {

   // you can use api and something else here

 };

}

總結(jié)

同 redux-thunk 非常流行的庫 redux-saga 一樣,都是在 redux 中做異步請求等副作用。Redux 相關(guān)的系列文章就暫時寫到這部分為止,下次會寫其他系列。

分享本文至:

日歷

鏈接

個人資料

藍藍設(shè)計的小編 http://www.bouu.cn

存檔