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);
      }
    }
    
  • 相关阅读:
    Python基础5_字典,集合
    Python基础3_基本数据类型,字符串,for循环
    Python基础2_while循环,格式化输出,基本运算符,编码,
    Python基础1_初识,注释,变量,if语句
    编写高质量代码[读书笔记]
    php地方天气
    [head first php&mysql]读书笔记-基本的安全信息(第五章)
    上传本地图片
    检测IE
    underscore源码解析(实用的功能)
  • 原文地址:https://www.cnblogs.com/jinkspeng/p/4821340.html
Copyright © 2011-2022 走看看