applyMiddleware

2018-02-24 15:28 更新

applyMiddleware(...middlewares)

使用包含自定義功能的 middleware 來擴展 Redux 是一種推薦的方式。Middleware 可以讓你包裝 store 的 dispatch 方法來達到你想要的目的。同時, middleware 還擁有“可組合”這一關(guān)鍵特性。多個 middleware 可以被組合到一起使用,形成 middleware 鏈。其中,每個 middleware 都不需要關(guān)心鏈中它前后的 middleware 的任何信息。

Middleware 最常見的使用場景是無需引用大量代碼或依賴類似 Rx 的第三方庫實現(xiàn)異步 actions。這種方式可以讓你像 dispatch 一般的 actions 那樣 dispatch 異步 actions

例如,redux-thunk 支持 dispatch function,以此讓 action creator 控制反轉(zhuǎn)。被 dispatch 的 function 會接收 dispatch 作為參數(shù),并且可以異步調(diào)用它。這類的 function 就稱為 thunk。另一個 middleware 的示例是 redux-promise。它支持 dispatch 一個異步的 Promise action,并且在 Promise resolve 后可以 dispatch 一個普通的 action。

Middleware 并不需要和 createStore 綁在一起使用,也不是 Redux 架構(gòu)的基礎(chǔ)組成部分,但它帶來的益處讓我們認為有必要在 Redux 核心中包含對它的支持。因此,雖然不同的 middleware 可能在易用性和用法上有所不同,它仍被作為擴展 dispatch 的唯一標準的方式。

參數(shù)

  • ...middlewares (arguments): 遵循 Redux middleware API 的函數(shù)。每個 middleware 接受 StoredispatchgetState 函數(shù)作為命名參數(shù),并返回一個函數(shù)。該函數(shù)會被傳入被稱為 next 的下一個 middleware 的 dispatch 方法,并返回一個接收 action 的新函數(shù),這個函數(shù)可以直接調(diào)用 next(action),或者在其他需要的時刻調(diào)用,甚至根本不去調(diào)用它。調(diào)用鏈中最后一個 middleware 會接受真實的 store 的 dispatch 方法作為 next 參數(shù),并借此結(jié)束調(diào)用鏈。所以,middleware 的函數(shù)簽名是 ({ getState, dispatch }) => next => action。

返回值

(Function) 一個應用了 middleware 后的 store enhancer。這個 store enhancer 就是一個函數(shù),并且需要應用到 createStore。它會返回一個應用了 middleware 的新的 createStore。

示例: 自定義 Logger Middleware

import { createStore, applyMiddleware } from 'redux';
import todos from './reducers';

function logger({ getState }) {
  return (next) => (action) => {
    console.log('will dispatch', action);

    // 調(diào)用 middleware 鏈中下一個 middleware 的 dispatch。
    let returnValue = next(action);

    console.log('state after dispatch', getState());

    // 一般會是 action 本身,除非
    // 后面的 middleware 修改了它。
    return returnValue;
  };
}

let createStoreWithMiddleware = applyMiddleware(logger)(createStore);
let store = createStoreWithMiddleware(todos, ['Use Redux']);

store.dispatch({
  type: 'ADD_TODO',
  text: 'Understand the middleware'
});
// (將打印如下信息:)
// will dispatch: { type: 'ADD_TODO', text: 'Understand the middleware' }
// state after dispatch: ['Use Redux', 'Understand the middleware']

示例: 使用 Thunk Middleware 來做異步 Action

import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import * as reducers from './reducers';

// 調(diào)用 applyMiddleware,使用 middleware 增強 createStore:
let createStoreWithMiddleware = applyMiddleware(thunk)(createStore);

// 像原生 createStore 一樣使用。
let reducer = combineReducers(reducers);
let store = createStoreWithMiddleware(reducer);

function fetchSecretSauce() {
  return fetch('https://www.google.com/search?q=secret+sauce');
}

// 這些是你已熟悉的普通 action creator。
// 它們返回的 action 不需要任何 middleware 就能被 dispatch。
// 但是,他們只表達「事實」,并不表達「異步數(shù)據(jù)流」

function makeASandwich(forPerson, secretSauce) {
  return {
    type: 'MAKE_SANDWICH',
    forPerson,
    secretSauce
  };
}

function apologize(fromPerson, toPerson, error) {
  return {
    type: 'APOLOGIZE',
    fromPerson,
    toPerson,
    error
  };
}

function withdrawMoney(amount) {
  return {
    type: 'WITHDRAW',
    amount
  };
}

// 即使不使用 middleware,你也可以 dispatch action:
store.dispatch(withdrawMoney(100));

// 但是怎樣處理異步 action 呢,
// 比如 API 調(diào)用,或者是路由跳轉(zhuǎn)?

// 來看一下 thunk。
// Thunk 就是一個返回函數(shù)的函數(shù)。
// 下面就是一個 thunk。

function makeASandwichWithSecretSauce(forPerson) {

  // 控制反轉(zhuǎn)!
  // 返回一個接收 `dispatch` 的函數(shù)。
  // Thunk middleware 知道如何把異步的 thunk action 轉(zhuǎn)為普通 action。

  return function (dispatch) {
    return fetchSecretSauce().then(
      sauce => dispatch(makeASandwich(forPerson, sauce)),
      error => dispatch(apologize('The Sandwich Shop', forPerson, error))
    );
  };
}

// Thunk middleware 可以讓我們像 dispatch 普通 action 
// 一樣 dispatch 異步的 thunk action。

store.dispatch(
  makeASandwichWithSecretSauce('Me')
);

// 它甚至負責回傳 thunk 被 dispatch 后返回的值,
// 所以可以繼續(xù)串連 Promise,調(diào)用它的 .then() 方法。

store.dispatch(
  makeASandwichWithSecretSauce('My wife')
).then(() => {
  console.log('Done!');
});

// 實際上,可以寫一個 dispatch 其它 action creator 里
// 普通 action 和異步 action 的 action creator,
// 而且可以使用 Promise 來控制數(shù)據(jù)流。

function makeSandwichesForEverybody() {
  return function (dispatch, getState) {
    if (!getState().sandwiches.isShopOpen) {

      // 返回 Promise 并不是必須的,但這是一個很好的約定,
      // 為了讓調(diào)用者能夠在異步的 dispatch 結(jié)果上直接調(diào)用 .then() 方法。

      return Promise.resolve();
    }

    // 可以 dispatch 普通 action 對象和其它 thunk,
    // 這樣我們就可以在一個數(shù)據(jù)流中組合多個異步 action。

    return dispatch(
      makeASandwichWithSecretSauce('My Grandma')
    ).then(() =>
      Promise.all([
        dispatch(makeASandwichWithSecretSauce('Me')),
        dispatch(makeASandwichWithSecretSauce('My wife'))
      ])
    ).then(() =>
      dispatch(makeASandwichWithSecretSauce('Our kids'))
    ).then(() =>
      dispatch(getState().myMoney > 42 ?
        withdrawMoney(42) :
        apologize('Me', 'The Sandwich Shop')
      )
    );
  };
}

// 這在服務端渲染時很有用,因為我可以等到數(shù)據(jù)
// 準備好后,同步的渲染應用。

store.dispatch(
  makeSandwichesForEverybody()
).then(() =>
  response.send(React.renderToString(<MyApp store={store} />))
);

// 也可以在任何導致組件的 props 變化的時刻
// dispatch 一個異步 thunk action。

import { connect } from 'react-redux';
import { Component } from 'react';

class SandwichShop extends Component {
  componentDidMount() {
    this.props.dispatch(
      makeASandwichWithSecretSauce(this.props.forPerson)
    );
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.forPerson !== this.props.forPerson) {
      this.props.dispatch(
        makeASandwichWithSecretSauce(nextProps.forPerson)
      );
    }
  }

  render() {
    return <p>{this.props.sandwiches.join('mustard')}</p>
  }
}

export default connect(
  state => ({
    sandwiches: state.sandwiches
  })
)(SandwichShop);

小貼士

  • Middleware 只是包裝了 store 的 dispatch 方法。技術(shù)上講,任何 middleware 能做的事情,都可能通過手動包裝 dispatch 調(diào)用來實現(xiàn),但是放在同一個地方統(tǒng)一管理會使整個項目的擴展變的容易得多。

  • 如果除了 applyMiddleware,你還用了其它 store enhancer,一定要把 applyMiddleware 放到組合鏈的前面,因為 middleware 可能會包含異步操作。比如,它應該在 redux-devtools 前面,否則 DevTools 就看不到 Promise middleware 里 dispatch 的 action 了。

  • 如果你想有條件地使用 middleware,記住只 import 需要的部分:

let middleware = [a, b];
if (process.env.NODE_ENV !== 'production') {
  let c = require('some-debug-middleware');
  let d = require('another-debug-middleware');
  middleware = [...middleware, c, d];
}
const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore);

這樣做有利于打包時去掉不需要的模塊,減小打包文件大小。

  • 有想過 applyMiddleware 本質(zhì)是什么嗎?它肯定是比 middleware 還強大的擴展機制。實際上,applyMiddleware 只是被稱為 Redux 最強大的擴展機制的 store enhancers 中的一個范例而已。你不太可能需要實現(xiàn)自己的 store enhancer。另一個 store enhancer 示例是 redux-devtools。Middleware 并沒有 store enhancer 強大,但開發(fā)起來卻是更容易的。

  • Middleware 聽起來比實際難一些。真正理解 middleware 的唯一辦法是了解現(xiàn)有的 middleware 是如何工作的,并嘗試自己實現(xiàn)。需要的功能可能錯綜復雜,但是你會發(fā)現(xiàn)大部分 middleware 實際上很小,只有 10 行左右,是通過對它們的組合使用來達到最終的目的。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號