Redux-Thunk - 异步动作创建者承诺并且链接不起作用

时间:2018-01-04 21:05:23

标签: javascript reactjs redux redux-thunk redux-promise

我正在尝试发送一个动作。我找到了一些行动的例子,但没有我的那么复杂。

你能给我一个暗示吗?我做错了什么?

我正在使用TypeScript,并且最近删除了所有类型并尽可能简化了我的代码。

我正在使用redux-thunk和redux-promise,如下所示:

import { save } from 'redux-localstorage-simple';
import thunkMiddleware from 'redux-thunk';
import promiseMiddleware from 'redux-promise';

const middlewares = [
        save(),
        thunkMiddleware,
        promiseMiddleware,
    ];
const store = createStore(
        rootReducer(appReducer),
        initialState,
        compose(
            applyMiddleware(...middlewares),
            window['__REDUX_DEVTOOLS_EXTENSION__'] ? window['__REDUX_DEVTOOLS_EXTENSION__']() : f => f,
        ),
    );

组件 - Foo组件:

import actionFoo from 'js/actions/actionFoo';
import React, { Component } from 'react';
import { connect } from 'react-redux';

class Foo {
    constructor(props) {
        super(props);
        this._handleSubmit = this._handleSubmit.bind(this);
    }
    _handleSubmit(e) {
        e.preventDefault();
        this.props.doActionFoo().then(() => {
            // this.props.doActionFoo returns undefined
        });
    }
    render() {
        return <div onClick={this._handleSubmit}/>;
    }
}

const mapStateToProps = ({}) => ({});

const mapDispatchToProps = {
    doActionFoo: actionFoo,
};

export { Foo as PureComponent };
export default connect(mapStateToProps, mapDispatchToProps)(Foo);

动作 - actionFoo:

export default () => authCall({
    types: ['REQUEST', 'SUCCESS', 'FAILURE'],
    endpoint: `/route/foo/bar`,
    method: 'POST',
    shouldFetch: state => true,
    body: {},
});

操作 - AuthCall:

// extremly simplified
export default (options) => (dispatch, getState) => dispatch(apiCall(options));

行动 - ApiCall:

export default (options) => (dispatch, getState) => {
    const { endpoint, shouldFetch, types } = options;

    if (shouldFetch && !shouldFetch(getState())) return Promise.resolve();

    let response;
    let payload;

    dispatch({
        type: types[0],
    });

    return fetch(endpoint, options)
        .then((res) => {
            response = res;
            return res.json();
        })
        .then((json) => {
            payload = json;

            if (response.ok) {
                return dispatch({
                    response,
                    type: types[1],
                });
            }
            return dispatch({
                response,
                type: types[2],
            });
        })
        .catch(err => dispatch({
            response,
            type: types[2],
        }));
};

2 个答案:

答案 0 :(得分:5)

来自redux-thunk

  

Redux Thunk中间件允许您编写返回的动作创建者   一个函数而不是一个动作

所以这意味着它无法处理你的承诺。您必须添加redux-promise以支持承诺

  

默认导出是中间件功能。如果收到承诺,   它会派遣承诺的已解决价值。它不会   如果承诺拒绝,则发送任何内容。

redux-thunkredux-promise之间的差异,您可以阅读here

答案 1 :(得分:4)

好的,几个小时后,我找到了解决方案。在任何其他中间件之前,redux-thunk必须先行。因为中间件是从右到左调用的,所以redux-thunk返回是最后一个链,因此返回Promise。

import thunkMiddleware from 'redux-thunk';

const middlewares = [
        thunkMiddleware,
        // ANY OTHER MIDDLEWARE,
    ];
const store = createStore(
        rootReducer(appReducer),
        initialState,
        compose(
            applyMiddleware(...middlewares),
            window['__REDUX_DEVTOOLS_EXTENSION__'] ? window['__REDUX_DEVTOOLS_EXTENSION__']() : f => f,
        ),
    );