1

我运行redux-loop 官方示例,稍作改动:

  1. 而不是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 接收的是一个函数而不是实际的用户对象?

4

1 回答 1

2

为什么 reducer 接收的是一个函数而不是实际的用户对象?

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

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

您可能打算这样做:

return new Promise((res, rej) => setTimeout(() => res(userId), 1000))
于 2018-10-27T13:14:50.843 回答