自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

推薦使用并手寫實(shí)現(xiàn)Redux-actions原理

開(kāi)發(fā) 前端
第一次見(jiàn)到主要是接手公司原有的項(xiàng)目,發(fā)現(xiàn)有之前的大佬在處理redux的時(shí)候引入了它。發(fā)現(xiàn)也確實(shí) 使得 在對(duì)redux的處理上方便了許多,而我為了更好地使用一個(gè)組件或者插件,都會(huì)去去嘗試閱讀源碼并寫成文章 ,這個(gè)也不例外。發(fā)現(xiàn)也確實(shí)有意思,推薦大家使用redux的時(shí)候也引入redux-actions。

[[358493]]

一、前言

為什么介紹redux-actions呢?

第一次見(jiàn)到主要是接手公司原有的項(xiàng)目,發(fā)現(xiàn)有之前的大佬在處理redux的時(shí)候引入了它。

發(fā)現(xiàn)也確實(shí) 使得 在對(duì)redux的處理上方便了許多,而我為了更好地使用一個(gè)組件或者插件,都會(huì)去去嘗試閱讀源碼并寫成文章 ,這個(gè)也不例外。

發(fā)現(xiàn)也確實(shí)有意思,推薦大家使用redux的時(shí)候也引入redux-actions

在這里就介紹一下其使用方式,并且自己手寫實(shí)現(xiàn)一個(gè)簡(jiǎn)單的redux-actions

二、介紹

學(xué)習(xí) redux 中,總覺(jué)得 action 和 reducer 的代碼過(guò)于呆板,比如

2.1 創(chuàng)建action

  1. let increment = ()=>({type:"increment"}) 

2.2 reducer

  1. let reducer = (state,action)=>{ 
  2.     switch(action.type){ 
  3.       case "increment":return {count:state.count+1};break; 
  4.       case "decrement":return {count:state.count-1};break; 
  5.       default:return state; 
  6.     } 

2.3 觸發(fā)action

  1. dispatch(increment()) 

綜上所示,我們難免會(huì)覺(jué)得 increment 和 reducer 做一個(gè)小 demo 還行,遇到邏輯偏復(fù)雜的項(xiàng)目后,項(xiàng)目管理維護(hù)就呈現(xiàn)弊端了。所以最后的方式就是將它們獨(dú)立出來(lái),同時(shí)在 reducer 中給與開(kāi)發(fā)者更多的主動(dòng)權(quán),不能僅停留在數(shù)字的增增減減。

redux-actions主要函數(shù)有createAction、createActions、handleAction、handleActions、combineActions。

基本上就是只有用到createAction,handleActions,handleAction

所以這里我們就只討論這三個(gè)個(gè)。

三、 認(rèn)識(shí)與手寫createAction()

3.1 用法

一般創(chuàng)建Action方式:

  1. let increment = ()=>({type:"increment"}) 
  2. let incrementObj = increment();// { type:"increment"

使用createAction 創(chuàng)建 action

  1. import { createAction } from 'redux-actions'
  2. const increment = createAction('increment'); 
  3. let incrementObj = increment();// { type:"increment"
  4. let objincrement = increment(10);// {type:"increment",paylaod:10} 

我們可以看到

  1. let increment = ()=>({type:"increment"}) 
  2. let incrementObj = increment();// { type:"increment"

  1. const increment = createAction('increment'); 
  2. let incrementObj = increment();// { type:"increment"

是等效的,那為什么不直接用傳統(tǒng)方式呢?

不難發(fā)現(xiàn)有兩點(diǎn):

  1. 傳統(tǒng)方式,需要自己寫個(gè)函數(shù)來(lái)返回incrementObj,而利用封裝好的createAtion就不用自己寫函數(shù)
  2. 傳統(tǒng)方式,在返回的incrementObj若是有payload需要自己添加上去,這是多么麻煩的事情啊,你看下面的代碼,如此的不方便。但是用了createAction返回的increment,我們添加上payload,十分簡(jiǎn)單,直接傳個(gè)參數(shù),它就直接把它作為payload的值了。
  1. let increment = ()=>({type:"increment",payload:123}) 

3.2 原理實(shí)現(xiàn)

我們先實(shí)現(xiàn)個(gè)簡(jiǎn)單,值傳入 type參數(shù)的,也就是實(shí)現(xiàn)下面這段代碼的功能

  1. const increment = createAction('increment'); 
  2. let incrementObj = increment();// { type:"increment"

我們發(fā)現(xiàn)createAction('increment')()才返回最終的action對(duì)象。這不就是個(gè)柯里化函數(shù)嗎?

所以我們可以非常簡(jiǎn)單的寫出來(lái),如下面代碼所示,我們把type類型當(dāng)作action對(duì)象的一個(gè)屬性了

  1. function createAction(type) { 
  2.     return () => { 
  3.         const action = { 
  4.             type 
  5.         }; 
  6.         return action
  7.     }; 

好了現(xiàn)在,現(xiàn)在實(shí)現(xiàn)下面這個(gè)功能,也就是有payload的情況

  1. const increment = createAction('increment'); 
  2. let objincrement = increment(10);// {type:"increment",paylaod:10} 

很明顯,這個(gè)payload是 在createAction('increment')返回的函數(shù)的參數(shù),所以我們輕而易舉地給action添加上了payload。

  1. function createAction(type) { 
  2.     return (payload) => { 
  3.         const action = { 
  4.             type, 
  5.             payload 
  6.         }; 
  7.         return action
  8.     }; 

但是像第一種情況我們是不傳payload的,也就是說(shuō)返回的action是不希望帶有payload的,但是這里我們寫成這樣就是 默認(rèn)一定要傳入payload的了。

所以我們需要添加個(gè)判斷,當(dāng)不傳payload的時(shí)候,action就不添加payload屬性。

  1. function createAction(type) { 
  2.     return (payload) => { 
  3.         const action = { 
  4.             type, 
  5.         }; 
  6.         if(payload !== undefined){ 
  7.             action.payload = payload 
  8.         } 
  9.         return action
  10.     }; 

在實(shí)際項(xiàng)目中我更喜歡下面這種寫法,但它是等價(jià)于上面這種寫法的

  1. function createAction(type) { 
  2.     return (payload) => { 
  3.         const action = { 
  4.             type, 
  5.             ...payload?{payload}:{} 
  6.         }; 
  7.         return action
  8.     }; 

其實(shí)createAction的參數(shù)除了type,還可以傳入一個(gè)回調(diào)函數(shù),這個(gè)函數(shù)表示對(duì)payload的處理。

  1. const increment = createAction('increment'); 
  2. let objincrement = increment(10);// {type:"increment",paylaod:10} 

像上面的代碼所示,我們希望的是傳入10之后是返回的action中的payload是我們傳入的2倍數(shù)

  1. const increment = createAction('increment',(t)=> t * 2); 
  2. let objincrement = increment(10);// {type:"increment",paylaod:20} 

現(xiàn)在,就讓我們實(shí)現(xiàn)一下。

function createAction(type,payloadCreator) { return (payload) => { const action = { type, }; if(payload !== undefined){ action.payload = payloadCreator(payload) } return action; };}

  1. function createAction(type,payloadCreator) { 
  2.     return (payload) => { 
  3.         const action = { 
  4.             type, 
  5.         }; 
  6.         if(payload !== undefined){ 
  7.             action.payload = payloadCreator(payload) 
  8.         } 
  9.         return action
  10.     }; 

太簡(jiǎn)單了吧!但是我們又犯了前邊同樣的錯(cuò)誤,就是我們使用createAction的時(shí)候,不一定會(huì)傳入payloadCreator這個(gè)回調(diào)函數(shù),所以我們還需要判斷下

  1. function createAction(type,payloadCreator) { 
  2.     return (payload) => { 
  3.         const action = { 
  4.             type, 
  5.         }; 
  6.         if(payload !== undefined){ 
  7.             action.payload = payloadCreator?payloadCreator(payload):payload 
  8.         } 
  9.         return action
  10.     }; 

完美。

接下來(lái)看看 redux-action的 handleActions吧

四、認(rèn)識(shí)handleActions

我們先看看傳統(tǒng)的reducer是怎么使用的

  1. let reducer = (state,action)=>{ 
  2.     switch(action.type){ 
  3.       case "increment":return {count:state.count+1};break; 
  4.       case "decrement":return {count:state.count-1};break; 
  5.       default:return state; 
  6.     } 

再看看使用了handleActions

  1. const INCREMENT = "increment" 
  2. const DECREMENT = "decrement" 
  3. var reducer = handleActions({ 
  4.     [INCREMENT]: (state, action) => ({ 
  5.       counter: state.counter + action.payload 
  6.     }), 
  7.     [DECREMENT]: (state, action) => ({ 
  8.       counter: state.counter - action.payload 
  9.     }) 
  10. },initstate) 

這里大家不要被{[DECREMENT]:(){}} 的寫法嚇住哈,就是把屬性寫成變量了而已。

我們?cè)诳刂婆_(tái) console.log(reducer) 看下結(jié)果

圖片

最后返回的就是一個(gè) reducer 函數(shù)。

這樣就實(shí)現(xiàn)了 reducer 中功能化的自由,想寫什么程序,我們只要寫在

  1. {[increment]:(state,action)=>{}}  

這個(gè)函數(shù)內(nèi)就行,同時(shí)也可以把這些函數(shù)獨(dú)立成一個(gè)文件,再引入進(jìn)來(lái)就行

  1. import {increment,decrement}from "./reducers.js" 
  2. var initstate = {count:0} 
  3. var reducer = createReducer({ 
  4.     [INCREMENT]: increment, 
  5.     [DECREMENT]: decrement 
  6. },initstate) 

reducers.js

  1. //reducers.js 
  2. export let increment = (state,action)=>({counter: state.counter + action.payload}) 
  3. export let decrement = (state,action)=>({counter: state.counter - action.payload}) 

可見(jiàn),

handleactions 可以簡(jiǎn)化 reducers 的寫法 不用那么多 switch 而且可以把函數(shù)獨(dú)立出來(lái),這樣reducer就再也不會(huì)有一大堆代碼了。

本來(lái)要講handleActions的實(shí)現(xiàn)了,但是在這之前,我們必須先講一下handleAction,對(duì),你仔細(xì)看,沒(méi)有s

五、認(rèn)識(shí)與手寫實(shí)現(xiàn)handleAction

5.1 用法

看下使用方式

  1. const incrementReducer = handleAction(INCREMENT, (state, action) => { 
  2.   return {counter: state.counter + action.payload} 
  3. }, initialState); 

可以看出來(lái),跟handleActions的區(qū)別 就是,handleAction生成的reducer是專門來(lái)處理一個(gè)action的。

5.2 原理實(shí)現(xiàn)

如果你看過(guò)redux原理的話(如果你沒(méi)看過(guò)的話,推薦你去看下我之前的文章Redux 源碼解析系列(一) -- Redux的實(shí)現(xiàn)思想),相信你應(yīng)該知道reducer(state,action)返回的結(jié)果是一個(gè)新的state,然后這個(gè)新的state會(huì)和舊的state進(jìn)行對(duì)比,如果發(fā)現(xiàn)兩者不一樣的話,就會(huì)重新渲染使用了state的組件,并且把新的state賦值給舊的state.

也就是說(shuō)handleAction()返回一個(gè)reducer函數(shù),然后incrementReducer()返回一個(gè)新的state。

先實(shí)現(xiàn)返回一個(gè)reducer函數(shù)

  1. function handleAction(type, callback) { 
  2.     return (state, action) => { 
  3.        
  4.     }; 

接下來(lái)應(yīng)當(dāng)是執(zhí)行reducer(state,action)是時(shí)候返回state,也就是執(zhí)行下面返回的這個(gè)

  1. (state, action) => { 
  2.        
  3. }; 

而其實(shí)就是執(zhí)行callback(state) 然后返回一個(gè)新的 state

  1. function handleAction(type, callback) { 
  2.     return (state, action) => { 
  3.          
  4.       return callback(state) 
  5.     }; 

或許你會(huì)有疑問(wèn),為什么要這么搞,而不直接像下面這樣,就少了一層包含。

  1. function handleAction(state,type, callback) { 
  2.     return callback(state) 

這才是它的巧妙之處。它在handleAction()返回的reducer()時(shí),可不一定會(huì)執(zhí)行callback(state),只有handleAction傳入的type跟reducer()中傳入的action.type匹配到了才會(huì)執(zhí)行,否則就直接return state。表示沒(méi)有任何處理

  1. function handleAction(type, callback) { 
  2.     return (state, action) => { 
  3.          
  4.       return callback(state) 
  5.     }; 

因此我們需要多加一層判斷

  1. function handleAction(type, callback) { 
  2.     return (state, action) => { 
  3.         if (action.type !== type) { 
  4.             return state; 
  5.         } 
  6.         return callback(state) 
  7.     }; 

多么完美啊!

好了現(xiàn)在我們來(lái)實(shí)現(xiàn)下handleActions

六、handleActions原理實(shí)現(xiàn)

  1. function handleActions(handlers, defaultState) { 
  2.     const reducers = Object.keys(handlers).map(type => { 
  3.         return handleAction(type, handlers[type]); 
  4.     }); 
  5.     const reducer = reduceReducers(...reducers) 
  6.     return (state = defaultState, action) => reducer(state, action

看,就這幾行代碼,是不是很簡(jiǎn)單,不過(guò)應(yīng)該不好理解,不過(guò)沒(méi)關(guān)系,我依舊將它講得粗俗易懂。

我們拿上面用到的例子來(lái)講好了

  1. var reducer = handleActions({ 
  2.     [INCREMENT]: (state, action) => ({ 
  3.       counter: state.counter + action.payload 
  4.     }), 
  5.     [DECREMENT]: (state, action) => ({ 
  6.       counter: state.counter - action.payload 
  7.     }) 
  8. },initstate) 

  1.     [INCREMENT]: (state, action) => ({ 
  2.       counter: state.counter + action.payload 
  3.     }), 
  4.     [DECREMENT]: (state, action) => ({ 
  5.       counter: state.counter - action.payload 
  6.     }) 
  7. } 

上面這個(gè)對(duì)象,經(jīng)過(guò)下面的代碼之后

  1. const reducers = Object.keys(handlers).map(type => { 
  2.         return handleAction(type, handlers[type]); 
  3.     }); 

返回的reducer,其實(shí)就是

  1.   handleAction(INCREMENT,(state, action) => ({ 
  2.       counter: state.counter + action.payload 
  3.   })), 
  4.   handleAction(DECREMENT,(state, action) => ({ 
  5.       counter: state.counter + action.payload 
  6.   })), 

為什么要變成一個(gè)handleAction的數(shù)組,

我大概想到了,是想每次dispatch(action)的時(shí)候,就要遍歷去執(zhí)行這個(gè)數(shù)組中的所有handleAction。

那豈不是每個(gè)handleAction返回的reducer都要執(zhí)行?確實(shí),但是別忘了我們上面講到的,如果handleAction 判斷到 type和action.type 是不會(huì)對(duì)state進(jìn)行處理的而是直接返回state

  1. function handleAction(type, callback) { 
  2.     return (state, action) => { 
  3.         if (action.type !== type) { 
  4.             return state; 
  5.         } 
  6.         return callback(state) 
  7.     }; 

沒(méi)有即使每個(gè) handleAction 都執(zhí)行了也沒(méi)關(guān)系

那應(yīng)該怎么遍歷執(zhí)行,用map,forEach?不,都不對(duì)。我們看回源碼

  1. function handleActions(handlers, defaultState) { 
  2.     const reducers = Object.keys(handlers).map(type => { 
  3.         return handleAction(type, handlers[type]); 
  4.     }); 
  5.     const reducer = reduceReducers(...reducers) 
  6.     return (state = defaultState, action) => reducer(state, action

使用了

  1. const reducer = reduceReducers(...reducers) 

用了reduceReducers這個(gè)方法,顧名思義,看這方法名,意思就是用reduce這個(gè)來(lái)遍歷執(zhí)行reducers這個(gè)數(shù)組。也就是這個(gè)數(shù)組。

  1.   handleAction(INCREMENT,(state, action) => ({ 
  2.       counter: state.counter + action.payload 
  3.   })), 
  4.   handleAction(DECREMENT,(state, action) => ({ 
  5.       counter: state.counter + action.payload 
  6.   })), 

我們看下reduceReducers的內(nèi)部原理

  1. function reduceReducers(...args) { 
  2.     const reducers = args; 
  3.     return (prevState, value) => { 
  4.         return reducers.reduce((newState, reducer, index) => { 
  5.             return reducer(newState, value); 
  6.         }, prevState); 
  7.     }; 
  8. }; 

我們發(fā)現(xiàn)將reducers這個(gè)數(shù)組放入reduceReducers,然后執(zhí)行reduceReducers,就會(huì)返回

  1. (prevState, value) => { 
  2.     return reducers.reduce((newState, reducer, index) => { 
  3.         return reducer(newState, value); 
  4.     }, prevState); 
  5. }; 

這個(gè)方法,也就是說(shuō)執(zhí)行這個(gè)方法就會(huì) 執(zhí)行

  1. return reducers.reduce((newState, reducer, index) => { 
  2.         return reducer(newState, value); 
  3.     }, prevState); 

也就是會(huì)使用reduce遍歷執(zhí)行reducers,為什么要用reduce來(lái)遍歷呢?

這是因?yàn)樾枰焉弦粋€(gè)handleAction執(zhí)行后返回的state傳遞給下一個(gè)。

這個(gè)思想有一點(diǎn)我們之間之前講的關(guān)于compose函數(shù)的思想,感興趣的話,可以去看一下【前端進(jìn)階之認(rèn)識(shí)與手寫compose方法】

  1. function handleActions(handlers, defaultState) { 
  2.     const reducers = Object.keys(handlers).map(type => { 
  3.         return handleAction(type, handlers[type]); 
  4.     }); 
  5.     const reducer = reduceReducers(...reducers) 
  6.     return (state = defaultState, action) => reducer(state, action

現(xiàn)在也就是說(shuō)這里的reducer是reduceReducers(...reducers)返回的結(jié)果,也就

  1. reducer = (prevState, value) => { 
  2.     return reducers.reduce((newState, reducer, index) => { 
  3.         return reducer(newState, value); 
  4.     }, prevState); 
  5. }; 

而handleActions返回

  1. (state = defaultState, action) => reducer(state, action

也就是說(shuō)handleActions其實(shí)是返回這樣一個(gè)方法。

  1. (state = defaultState, action) => { 
  2.     return reducers.reduce((newState, reducer, index) => { 
  3.         return reducer(newState, value); 
  4.     }, state); 

好家伙,在handleAction之間利用reduce來(lái)傳遞state,真是個(gè)好方法,學(xué)到了。

貼一下github 的redux-action的源碼地址,感興趣的朋友可以親自去閱讀一下,畢竟本文是做了簡(jiǎn)化的 redux-actions:https://github.com/redux-utilities/redux-actions

參考文章

  • 【React系列---FSA知識(shí)】https://segmentfault.com/a/1190000010113847
  • 【Redux-actions 的用法】https://zhuanlan.zhihu.com/p/273569290
  • 【前端進(jìn)階之認(rèn)識(shí)與手寫compose方法】
  • Redux 源碼解析系列(一) -- Redux的實(shí)現(xiàn)思想)

 

責(zé)任編輯:姜華 來(lái)源: 前端陽(yáng)光
相關(guān)推薦

2021-12-01 06:40:32

Bind原理實(shí)現(xiàn)

2020-07-03 17:20:07

Redux前端代碼

2021-11-30 06:56:58

CallApply函數(shù)

2018-03-06 15:05:30

數(shù)據(jù)庫(kù)連接池連接管道

2020-10-23 09:26:57

React-Redux

2023-05-11 07:25:57

ReduxMiddleware函數(shù)

2022-11-15 17:07:40

開(kāi)發(fā)自動(dòng)化前端

2019-09-23 19:30:27

reduxreact.js前端

2020-12-03 08:14:45

Axios核心Promise

2020-11-02 09:35:04

ReactHook

2009-12-30 15:26:02

Silverlight

2017-03-02 10:49:37

推薦算法原理實(shí)現(xiàn)

2024-02-20 08:08:43

2020-12-10 08:24:40

線程池線程方法

2021-12-12 21:01:12

CSS 技巧PurgeCss

2024-02-01 08:12:15

ReducerContext狀態(tài)

2021-07-16 07:57:34

ReduxDOM組件

2019-11-26 08:00:00

GitHubGitHub ActiAzure

2024-01-24 18:50:21

WebFTP服務(wù)器

2021-07-27 14:50:15

axiosHTTP前端
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)