簡單說明redux thunk的作用

2021-10-12 17:43:53 字數 1666 閱讀 5943

const store =

createstore

(thunk)

import

from

'./types'

//普通action

export

const

showall=(

)=>

}export

const

shownothing=(

)=>

}export

const

addtodo

=(todo)

=>

}//可多次dispatch的action

export

const

test

=(todo)

=>

(dispatch,getstate,extraargument)

=>

) console.

log(

getstate()

);//第二次dispatch

dispatch()

console.

log(

getstate()

);//隨便做其他事情

console.

log(

'隨便做其他事情'

)}

showallshownothingaddtodo是普通的action,返回物件。test是可以多次**的action。,在test裡面我們呼叫了兩次dispatch

test**為什麼那麼寫?接著看

這是原始碼,就幾行,吃驚吧。

function

createthunkmiddleware

(extraargument)

)=> next => action =>

return

next

(action);}

;}const thunk =

createthunkmiddleware()

;thunk.withextraargument = createthunkmiddleware;

export

default thunk;

簡單來說就是,就是判斷每個action:如果是function型別,就呼叫這個function(並傳入 dispatch 和 getstate 及 extraargument 為引數),而不是任由讓它到達 reducer,因為 reducer 是個純函式,redux 規定到達 reducer 的 action 必須是乙個 plain object 型別。

引數dispatch就是store.dispatch

引數getstate 就是store.getstate

現在應該能理解為什麼上面test**要那麼寫了吧

1.即如上所說,我需要在乙個action中觸發多個dispatch

2.action中做其他任何函式能做的事情,比如帶***的事情

參考文章

理解redux-thunk

FormatMessage簡單說明

常用引數簡介.formatmessage format message from system format message allocate buffer,null,lval,null,lptstr hlocal,0,null 第乙個引數是標誌,告訴這個formatmessage函式,我想要的特點...

Subversion 簡單說明

subversion 簡單說明 checkout 從源 管理伺服器取出 commit 提交更新的 到源 管理伺服器。update 從源 管理伺服器獲取 的最新更新。export 從源 管理伺服器匯出 匯出的 將脫離源 管理。revert 將當前資料恢復到最近與伺服器同步的版本,即放棄自己的所有未提交...

std deque簡單說明

本文 http blog.chinaunix.net u2 86575 showart 1734758.html std deque是乙個高效的雙端佇列,可以高效地進行插入和刪除操作。以sgi c stl為例 deque的基本結構是 有乙個map map中的元素是乙個記錄了乙個大小為512位元組的線...