为什么 redux-loop 操作会跳过所有中间件?

Why redux-loop actions skip all middlewares?

我运行redux-loop official example稍作改动:

  1. 我使用带超时的 promise 而不是 fetch
  2. 我添加了日志中间件(从 redux.js.org 教程中复制粘贴)。

副作用函数:

import {createStore, compose, applyMiddleware} from 'redux';
import {install, loop, Cmd} from 'redux-loop';

function fetchUser(userId) {
    return Promise.resolve((res, rej) => setTimeout(() => res(userId), 1000));
}

操作:

function initAction() {
    return {
        type: 'INIT'
    };
}

function userFetchSuccessfulAction(user) {
    return {
        type: 'USER_FETCH_SUCCESSFUL',
        user
    };
}

function userFetchFailedAction(err) {
    return {
        type: 'USER_FETCH_ERROR',
        err
    };
}

初始状态:

const initialState = {
        initStarted: false,
        user: null,
        error: null
    };

减速器:

function reducer(state = initialState, action) {
        console.log(action);  // I added this line
        switch (action.type) {
            case 'INIT':
                return loop(
                    {...state, initStarted: true},
                    Cmd.run(fetchUser, {
                        successActionCreator: userFetchSuccessfulAction,
                        failActionCreator: userFetchFailedAction,
                        args: ['1234']
                    })
                );

            case 'USER_FETCH_SUCCESSFUL':
                return {...state, user: action.user};

            case 'USER_FETCH_FAILED':
                return {...state, error: action.error};

            default:
                return state;
        }
    }

我的自定义日志中间件:

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

配置商店:

const enhancer = compose(
        applyMiddleware(logger),
        install()
    );

    const store = createStore(reducer, initialState, enhancer);

调度第一个动作以启动这一切:(我的代码)

store.dispatch(initAction());

输出:


如您所见,第二个操作跳过了我的日志中间件,而且日志的最后一行我也不清楚。为什么 reducer 收到的是函数而不是实际的用户对象?

Why the reducer received a function instead of the actual user object?

return Promise.resolve((res, rej) => setTimeout(() => res(userId), 1000));

Promise.resolve 用于创建已处于已解决状态的承诺。它希望您传入 promise 应该解析的值,在您的情况下,您已经要求它解析为一个函数。

您可能打算这样做:

return new Promise((res, rej) => setTimeout(() => res(userId), 1000))