剧场模式
首页前端ReactRedux 入门教程(React 进阶)

Redux 入门教程 #12 中间件

海外散仙厉飞雨 · 真仙发布于
6

https://redux.js.org/api-reference/createstore

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';
import { Provider } from 'react-redux';

const logger = store => next => action => {
  console.log('dispatching', action);
  let result = next(action);
  console.log('next state', store.getState());
  return result;
};

const error = store => next => action => {
  try {
    next(action)
  } catch(e) {
    console.log('error ' + e);
  }
};

// const logger = function(store) {
//   return function(next) {
//     return function(action) {
//       console.log('dispatching', action);
//       let result = next(action);
//       console.log('next state', store.getState());
//       return result;
//     }
//   }
// }

const store = createStore(rootReducer, {}, applyMiddleware(logger, error));

// store.subscribe(() => console.log("State updated!", store.getState()));

ReactDOM.render(
  <Provider store={ store }>
    <App />
  </Provider>,
  document.getElementById('root')
);

registerServiceWorker();

reducers/counter.js

const counter = (state = 1, action = {}) => {
  switch(action.type) {
    case 'INCREMENT':
      throw new Error('error in INCREMENT')
      // return state + 1;
    case 'DECREMENT':
      return state - 1;
    default: return state;
  }
}

export default counter;

5 条回复
  • MuYu · 金仙后期
    MuYu · 金仙后期 #1

    这里其实是有很多疑问没有解开的。
    applyMiddleware() 背后是有函数组合的思想的。
    中间件的写法为什么会是 store => next => action 的这种写法,这背后是函数柯里化的思想
    说到函数柯里化和函数组合,就不的不说到函数式编程的思想了

  • 海外散仙厉飞雨 · 真仙

    👍

  • xll · 道祖
    xll · 道祖 #3

    let next=store.dispatch;
    store.dispatch=(action)=>{}

  • netNowork · 金仙后期

    系统日志提示

  • netNowork · 金仙后期

    next () 应该怎么样理解 那块 逻辑有点不好理解

© 汕尾市求知科技有限公司 | 粤ICP备19038915号 | 在线学员:104

Top