Redux中介軟體之redux thunk使用詳解

2021-09-11 15:25:33 字數 1664 閱讀 7026

redux的核心概念其實很簡單:將需要修改的state都存入到store裡,發起乙個action用來描述發生了什麼,用reducers描述action如何改變state tree 。建立store的時候需要傳入reducer,真正能改變store中資料的是store.dispatch api。

1.概念dispatch乙個action之後,到達reducer之前,進行一些額外的操作,就需要用到middleware。你可以利用 redux middleware 來進行日誌記錄、建立崩潰報告、呼叫非同步介面或者路由等等。 換言之,中介軟體都是對store.dispatch()的增強

2.中介軟體的用法

import thunk from 'redux-thunk';

const store = createstore(

reducers,

);複製**

const store = createstore(

reducers,

);複製**

4.redux-thunk分析redux-thunk的原始碼node_modules/redux-thunk/src/index.js

function createthunkmiddleware(extraargument) ) => next => action => ;//面向1-3年前端人員

} //幫助突破技術瓶頸,提公升思維能力

const thunk = createthunkmiddleware();

thunk.withextraargument = createthunkmiddleware;

export default thunk;

複製**

redux-thunk中介軟體export default的就是createthunkmiddleware()過的thunk,再看createthunkmiddleware這個函式,返回的是乙個柯里化過的函式。我們再翻譯成es5的**容易看一點,

function createthunkmiddleware(extraargument) ) 

return next(action);

}//面向1-3年前端人員

}//幫助突破技術瓶頸,提公升思維能力

}複製**

可以看出來redux-thunk最重要的思想,就是可以接受乙個返回函式的action creator。如果這個action creator 返回的是乙個函式,就執行它,如果不是,就按照原來的next(action)執行。 正因為這個action creator可以返回乙個函式,那麼就可以在這個函式中執行一些非同步的操作。 例如:

export

function

addcount

() }

export

function

addcountasync

() ,2000)

}//面向1-3年前端人員

//幫助突破技術瓶頸,提公升思維能力

複製**

addcountasync函式就返回了乙個函式,將dispatch作為函式的第乙個引數傳遞進去,在函式內進行非同步操作就可以了。結語

redux中介軟體之redux thunk

redux的核心概念其實很簡單 將需要修改的state都存入到store裡,發起乙個action用來描述發生了什麼,用reducers描述action如何改變state tree 建立store的時候需要傳入reducer,真正能改變store中資料的是store.dispatch api。disp...

redux 中介軟體 redux thunk

什麼是中介軟體?中介軟體指的是redux的,不是react的。中間指的是action跟store之間,也就是對dispacth方的封裝,最原始的是直接將接受過來的物件直接傳遞給store,但是如果傳遞的是乙個函式的話,就不會將這直接傳遞給store,而是先執行這個函式。常見的中間有 redux de...

redux中介軟體原理

應用了如下的中介軟體 a,b,c 整個執行 action 的過程為 a b c dispatch c b a action 最右側的next action 返回的是應用傳入的action 該行為是由redux createstore原始碼中dispatch方法返回值決定的,不過一般都會return ...