middleware在dispatch之間,middleware全處理完才會到達reducer。如果我們想做logging、異步處理或錯誤記錄都可在此。applyMiddleware可以用來串連多個middleware,並按照加入的順執行,官網文件有手動演示middleware演進過程,從頭看一篇就能大致了解。
middleware diagram
middleware概念就像curry function呼叫一個function,再回傳一個function,詳情可以看官網文件一步一步演化。
var add = function(x) {
return function(y) {
return x + y;
};
};
var increment = add(1);
increment(2);
//3
log middleware example
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider, connect } from 'react-redux';
import reducer from './reducer';
import Counter from './Counter';
const logMiddleWare = store => next => action => {
console.log("Log Middleware:", action);
next(action);
}
const logIncrementMiddleware = store => next => action => {
if(action.type === 'INCREMENT') {
console.log(`Increment triggered: ${JSON.stringify(store.getState())}`);
}
next(action);
}
let store = createStore(reducer, applyMiddleware(logMiddleWare, logIncrementMiddleware));
ReactDOM.render(
<Provider store={store}>
<Counter />
</Provider>,
document.getElementById('app')
);
輸出log
官網的middleware文件看完後,會對middleware比較有感覺。但除了自己寫middleware外,也能使用第三方寫好的middleware,因為還不熟的關係我在Async Actions和Redux Thunk middleware迷失還轉不出來,等弄懂之後再分享給大家。
github repositories react-redux-counter
https://github.com/kwon44/react-redux-counter
參考資料
Middleware
https://redux.js.org/docs/advanced/Middleware.html
Advanced
https://redux.js.org/docs/advanced/