iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 28
0
Modern Web

30天React從入門到入坑系列 第 28

DAY28:react-redux middleware做什麼?

  • 分享至 

  • xImage
  •  

middleware在dispatch之間,middleware全處理完才會到達reducer。如果我們想做logging、異步處理或錯誤記錄都可在此。applyMiddleware可以用來串連多個middleware,並按照加入的順執行,官網文件有手動演示middleware演進過程,從頭看一篇就能大致了解。

middleware diagram
https://ithelp.ithome.com.tw/upload/images/20180116/20107317roipDobsNe.png

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
https://ithelp.ithome.com.tw/upload/images/20180116/20107317Z1edmtSqX4.png

官網的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/


上一篇
DAY27:react-redux simple counter
下一篇
DAY29:mobx-react什麼怪東西…?
系列文
30天React從入門到入坑30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言