如何在 reducer 之間共享 state?

許多用戶(hù)想在 reducer 之間共享數(shù)據(jù),但是 combineReducers 不允許此種行為。有許多可用的辦法,今天就一起討論這個(gè)問(wèn)題。
combineReducers(reducers)reducers (Object): 一個(gè)對(duì)象,它的值(value)對(duì)應(yīng)不同的 reducer 函數(shù),這些 reducer 函數(shù)后面會(huì)被合并成一個(gè)。
隨著應(yīng)用變得越來(lái)越復(fù)雜,可以考慮將 reducer 函數(shù)拆分成多個(gè)單獨(dú)的函數(shù),拆分后的每個(gè)函數(shù)負(fù)責(zé)獨(dú)立管理 state 的一部分。
rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})// rootReducer 將返回如下的 state 對(duì)象{potato: {// 由 potatoReducer 管理的 state 對(duì)象 ...},tomato: {// 由 tomatoReducer 管理的 state 對(duì)象 ...}}
那么問(wèn)題來(lái)了,將 reducer 函數(shù)拆分成多個(gè)單獨(dú)的函數(shù),reducer 之間無(wú)法共享 state 怎么辦呢?(由 potatoReducer 管理的 state 對(duì)象與由 tomatoReducer 管理的 state 對(duì)象,無(wú)法獲取對(duì)方的 state 值)。首先最簡(jiǎn)單的辦法是不要將 reducer 函數(shù)拆分成多個(gè)單獨(dú)的函數(shù),而是只使用一個(gè) reducer 函數(shù),就不會(huì)出現(xiàn)這個(gè)問(wèn)題了。
標(biāo)準(zhǔn)的做法是使用 Redux Thunk 中間件。要引入 redux-thunk 這個(gè)專(zhuān)門(mén)的庫(kù)才能使用。在 redux-thunk 的異步 action 創(chuàng)建函數(shù)能通過(guò) getState() 方法獲取所有的 state。
export function fetchPostsIfNeeded(subreddit) {// 注意這個(gè)函數(shù)也接收了 getState() 方法// 它讓你選擇接下來(lái) dispatch 什么。return (dispatch, getState) => {// todo...}}
只需牢記 reducer 僅僅是函數(shù),可以隨心所欲的進(jìn)行劃分和組合,而且也推薦將其分解成更小、可復(fù)用的函數(shù)。
總結(jié):如果一個(gè) reducer 想獲取其它 state 層的數(shù)據(jù),往往意味著 state 樹(shù)需要重構(gòu),需要讓單獨(dú)的 reducer 處理更多的數(shù)據(jù)。
