美文网首页
redux中间件--简单理解

redux中间件--简单理解

作者: 向前冲冲的蜗牛 | 来源:发表于2018-06-11 16:55 被阅读0次

    参考链接为:

    https://www.rails365.net/movies/redux-ru-men-jiao-cheng-12-zhong-jian-jian

    import React from 'react';
    import ReactDOM from 'react-dom';
    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();

    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;

    这是一个“日志和error处理的中间件”
    其中“next(action)”是一个走下一个中间建的意思,
    Logger的执行顺序是 输出
    (1)输出("dispatching",action);
    (2)next(action)是执行下一个中间件 就是 error
    如下:

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

    执行顺序是 :如果没有错误,则执行下一个中间件
    如果有错误,则输出 ("error",e)

    当点击“增加+1”按钮的时候,则出发action“ INCREMENT”,
    所以会触发一个错误,就是new Error(‘error in INCREMENT’)

    则整个页面显示的结果为:
    1)(dispatching,INCREMENT)
    2)(error,"error in INCREMENT")
    3)('next state', store.getState());

    相关文章

      网友评论

          本文标题:redux中间件--简单理解

          本文链接:https://www.haomeiwen.com/subject/qnizsftx.html