zoukankan      html  css  js  c++  java
  • react-redux(2)

    中间件

    机制:

    • 建立一个store.dispatch的链条,每个middleware是链条中的一个环节,传入的action对象逐步处理,直到最后出来是Javascript Plain Object;
    import { createStore, combineReducers, applyMiddleware } from 'redux';
    
    // applyMiddleware takes createStore() and returns// a function with a compatible API.
    let createStoreWithMiddleware = applyMiddleware(
      logger,
      crashReporter
    )(createStore);
    
    // Use it like you would use createStore()let todoApp = combineReducers(reducers);
    let store = createStoreWithMiddleware(todoApp);
    

    middleware

    `// Logs all actions and states after they are dispatched.
    const logger = store => next => action => {
      console.log('dispatching', action);
      let result = next(action);
      console.log('next state', store.getState());
      return result;
    };`
    
    • 每一个 Middleware 可以得到:
      • store: 通过store.getState获得最近的状态;以及通过原本的dispatch对象直接发布action对象;
      • next方法: 前一个Middleware返回的dispatch方法;

    Thunk

    • 实现传名调用(只在执行时求值)的临时函数;
    //Thunk middleware
    const thunk = store => next => action => {
      typeof action === 'function' ?
        action(store.dispatch, store.getState) :
        next(action);
    }
    
    • 加入这个中间件后,再action中定义异步的方法
    export function incrementIfOdd () {
      return (dispatch, getState) => {
        const {counter} = getState();
        if(counter % 2 === 0) return;
        dispatch(increment());
      }
    }
    
    export function incrementAsync(delay = 1000) {
      return dispatch => {
        setTimeout(()=> {
          dispatch(increment());
        }, delay);
      }
    }
    
  • 相关阅读:
    Spring Cloud(4):断路器(Hystrix)
    Spring Cloud(3):配置服务(Config)
    Spring Cloud(2):服务发现(Eureka)
    Docker常用命令
    Spring Cloud(1):概览
    Spring Cloud(0):目录
    Spring Boot JDBC:加载DataSource过程的源码分析及yml中DataSource的配置
    Java集合(7):散列与散列码
    [Linux]RabbitMQ
    [Linux]查看硬件及操作系统信息
  • 原文地址:https://www.cnblogs.com/jinkspeng/p/4821340.html
Copyright © 2011-2022 走看看