打造Redux中間件

打造Redux中間件

簡單的

基本中間件:

const customMiddleware = store => next => action => {
    if(action.type !== 'CUSTOM_ACT_TYPE') {
        return next(action)
        // 其他代碼
    }
}

使用:

import {createStore, applyMiddleware} from 'redux';
import reducer from './reducer';
import customMiddleware from './customMiddleware';

const store = createStore(reducer, applyMiddleware(customMiddleware));

store => next => action =>看起來很復雜有木有?;旧夏闶窃趯懸粋€一層一層往外返回的方法,調用的時候是這樣的:

let dispatched = null;
let next = actionAttempt => dispatched = actionAttempt;

const dispatch = customMiddleware(store)(next);

dispatch({
  type: 'custom',
  value: 'test'
});

你做的只是串行化的函數調用,并在每次的調用上傳入適當的參數。當我第一次看到這個的時候,我也被這么長的函數調用串驚呆了。但是,在讀了編寫redux測試之后就理解是怎么回事了。

所以現在我們理解了函數調用串是怎么工作的了,我們來解釋一下這個中間件的第一行代碼:

if(action.type !== 'custom') {
    return next(action);
}

應該有什么辦法可以區分什么action可以被中間件使用。在這個例子里,我們判斷action的type為非custom的時候就調用next方法,其他的會傳導到其他的中間件里知道reducer。

來點酷的

redux的官方指導里有幾個不錯的例子,我在這里詳細解釋一下。

我們有一個這樣的action:

dispatch({
  type: 'ajax',
  url: 'http://some-api.com',
  method: 'POST',
  body: state => ({
    title: state.title,
    description: state.description
  }),
  cb: response => console.log('finished', response)
})

我們要實現一個POST請求,然后調用cb這個回調方法??雌饋硎沁@樣的:

import fetch from 'isomorphic-fetch'

const ajaxMiddleware = store => next => action => {
    if(action.type !== 'ajax') return next(action);

    fetch(action.url, {
        method: action.method,
        body: JSON.stringify(action.body(store.getState()))
    }).then(response => response.json())
    .then(json => action.cb(json))
}

非常的簡單。你可以在中間件里調用redux提供的每一個方法。如果我們要回調方法dispatch更多的action該如何處理呢?

.then(json => action.cb(json, store.dispatch))

只要修改上例的最后一行就可以搞定。

然后在回調方法定義里,我們可以這樣:

cb: (response, dispatch) => dispatch(newAction(response))

As you can see, middleware is very easy to write in redux. You can pass store state back to actions, and so much more. If you need any help or if I didn’t go into detail enough, feel free to leave a comment below!

如你所見,redux中間件非常容易實現。

原文地址:https://reactjsnews.com/redux-middleware

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 學習必備要點: 首先弄明白,Redux在使用React開發應用時,起到什么作用——狀態集中管理 弄清楚Redux是...
    賀賀v5閱讀 8,947評論 10 58
  • 前言 本文 有配套視頻,可以酌情觀看。 文中內容因各人理解不同,可能會有所偏差,歡迎朋友們聯系我討論。 文中所有內...
    珍此良辰閱讀 11,942評論 23 111
  • http://gaearon.github.io/redux/index.html ,文檔在 http://rac...
    jacobbubu閱讀 80,058評論 35 198
  • “中間件”這個詞聽起來很恐怖,但它實際一點都不難。想更好的了解中間件的方法就是看一下那些已經實現了的中間件是怎么工...
    Jmingzi_閱讀 1,717評論 1 7
  • 年少的我們在心中都曾經住著一位男神,那是年少的怦然心動。或許是因為那一瞬間一見鐘情的動心;或許是因為那打籃球帥...
    娜麗麗的天地閱讀 284評論 0 0