redux 中的 redux thunk 中介軟體

2022-06-08 13:42:07 字數 1388 閱讀 1943

空閒時間把redux中的redux-thunk中介軟體回顧下,因為以前沒有寫部落格的習慣,都怪自己太年輕,好了

其實:用reducers描述action如何改變state tree 。建立store的時候需要傳入reducer,真正能改變store中資料的是store.dispatch api。

推薦 react 的官網

當然也可以這個  這個中文比較看的懂 ,哈哈

dispatch乙個action之後,到達reducer之前,進行一些額外的操作,就需要用到middleware。

你可以利用 redux middleware 來進行日誌記錄、建立崩潰報告、呼叫非同步介面或者路由等等

import thunk from 'redux-thunk';

const store =createstore(

reducers,

);即可以在reducer中進行一些非同步的操

const store =createstore(

reducers,

);

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

function

createthunkmiddleware(extraargument) ) => next => action =>

return

next(action);

};}const thunk =createthunkmiddleware();

thunk.withextraargument =createthunkmiddleware;

export

default thunk;

redux-thunk中介軟體export default的就是createthunkmiddleware()過的thunk,再看createthunkmiddleware這個函式,

返回的是乙個細化過的函式。 

redux-thunk最重要的思想,就是

可以接受乙個返回函式的action creator。

如果這個action creator 返回的是乙個函式,就執行它,如果不是,就按照原來的next(action)執行。

正因為這個action creator可以返回乙個函式,那麼就可以在這個函式中執行一些非同步的操作。 例如:

export function

addcount()

}export

function

addcountasync() ,2000)

}}

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

Redux中的重要概念

首先,先看看第一張圖,圖中展示了redux的單向資料流,以及action reducer和store這三個核心概念。下面就圍繞上圖,非別介紹action reducer和store這三個概念。action是乙個物件,用來代表所有會引起狀態 state 變化的行為 例如服務端的響應,頁面上的使用者操作...

react中redux的使用

1.安裝redux npm install redux 2.store的建立 src store index.js import from redux import reducer from reducer const store createstore reducer src store redu...

taro 中 redux 的使用

官方教程 首先需要先按照官方文件 安裝好redux tarojs redux和 tarojs redux h5 這裡我是以我使用的attabbar底部導航作為乙個例項 如果需要使用可以安裝 taro ui 後引入使用 在 src reducers index.ts 中引入並註冊我們需要新增的redu...